为什么我不能在ncurses中为printw提供字符串参数?

时间:2019-07-13 23:27:06

标签: c++ c++11 ncurses

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

#include <iostream>
#include <ncurses.h>
#include <string>

int main(){
  std::string mystring = "A sample string\n";

  // 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);

我要去哪里错了?我该如何纠正?

1 个答案:

答案 0 :(得分:1)

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

字符串文字声明(也称为“这是字符串文字”)的类型为const char[N],其中N是字符串的大小,包括空终止符。

std::string != const char[]

但是,可以使用此构造函数(找到的here)与std::string一起构建const char[]

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 string\n"; // 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 string\n";

  // 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();
}
相关问题