为什么我不能提供一个字符串参数来打印 ncurses?
Why can't I provide a string argument to printw in ncurses?
对于我正在编写的应用程序,我有一个字符串类型变量,我想在 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();
}
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 如何使用字符串文字作为宏参数
- 如何将可变长度参数联接为字符串
- 如何使用字符串find_first_of缓冲区形式(size_t n 参数)
- 具有字符串化的可变参数宏的现代/通用方法
- C++ 构造函数参数:字符串、整数、整数、整数
- 当C 中的系统调用conconculables时,参数字符串中的字符损失
- 模板参数字符串与整数
- #define 参数字符串化,但宽字符串 L " instead of "
- std::getline 用于 ifstream,使用参数字符串或 char *
- 通过参数字符串化宏调用模板函数
- 可变参数字符串比较
- 为什么位集的构造函数有参数字符串::charT 零,字符串::charT one)
- c++中stdbind在带有参数(字符串)的函数中的用法
- 当使用字符变量作为参数(字符串转换为字符)时,Std::rename()文件将不起作用
- C/ c++预处理器中的宏参数字符串化为宽字符串字面值
- 如何比较Visual C++中的参数字符串
- C++错误:推断出参数'T'字符串与常量字符的冲突类型 *
- 传递参数字符串,其中包含空格和引号
- 函数参数字符串通过引用传递