为什么我不能提供一个字符串参数来打印 ncurses?

Why can't I provide a string argument to printw in ncurses?

本文关键字:参数 字符串 一个 打印 ncurses 不能 为什么      更新时间:2023-10-16

对于我正在编写的应用程序,我有一个字符串类型变量,我想在 ncurses 窗口中显示它:

#include <iostream>
#include <ncurses.h>
#include <string>
int main(){
  std::string mystring = "A sample stringn";
  // Entering the ncurses window
  initscr();
  printw(mystring);
  getch();
  endwin();
}

这会在编译时引发以下错误:

test_app.cpp: In function ‘int main()’:
test_app.cpp:12:18: error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘const char*’ for argument ‘1’ to ‘int printw(const char*, ...)’
   printw(mystring);

我哪里出错了?我该如何纠正此问题?

c++ 中的一些关键概念:

字符串文字声明(又名"这是一个字符串文字"(的类型const char[N],其中 N 是字符串的大小,包括 null 终止符。

std::string != const char[]

但是,可以使用此构造函数(在此处找到(通过const char[]构造std::string

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );

其中CharT是特定于您的实现char等效的。

现在,请注意printw如何const char*。你不是在传递const char *printw,而是在传递std::string,它们不是隐式转换为const char *

我们有两种选择来解决您的问题...

1( 将字符串存储为 char[](又名 char *(:

#include <iostream>
#include <ncurses.h>
#include <string>
int main(){
  char mystring[] = "A sample stringn"; // Can decay to a char * implicitly.
  // Entering the ncurses window
  initscr();
  printw(mystring);
  getch();
  endwin();
}

2( 将std::string表示为char *

#include <iostream>
#include <ncurses.h>
#include <string>
int main(){
  std::string mystring = "A sample stringn";
  // Entering the ncurses window
  initscr();
  // Since c++ 11, mystring.data() is required to return a null-terminated char *.
  // If c++ version < c++11, use mystring.c_str().
  printw(mystring.data());  
  getch();
  endwin();
}