n0p*_*0pe 4 c++ string ncurses
我正在用C ++编写基于文本的游戏。在某个时候,我要求用户输入与不同玩游戏者相对应的用户名。
我目前正在从ncurses读取单个字符,如下所示:
move(y,x);
printw("Enter a char");
int char = getch();
Run Code Online (Sandbox Code Playgroud)
但是,我不确定如何输入字符串。我正在寻找类似的东西:
move(y,x);
printw("Enter a name: ");
std::string name = getstring();
Run Code Online (Sandbox Code Playgroud)
我已经看到了许多使用ncurses的不同指南,它们都使用一组其他函数没有的不同函数。据我所知,不赞成和不赞成使用的功能之间的界限不是很清楚。
这个怎么样?
std::string getstring()
{
std::string input;
// let the terminal do the line editing
nocbreak();
echo();
// this reads from buffer after <ENTER>, not "raw"
// so any backspacing etc. has already been taken care of
int ch = getch();
while ( ch != '\n' )
{
input.push_back( ch );
ch = getch();
}
// restore your cbreak / echo settings here
return input;
}
Run Code Online (Sandbox Code Playgroud)
我不鼓励使用替代*scanw()功能系列。您将在使用临时char []缓冲区,*scanf()具有所有问题的基础功能,加上*scanw()返回的状态说明ERR或OK代替扫描的项目数量,从而进一步降低了其实用性。
尽管getstr()(由用户indiv建议)看起来比*scanw()功能键更好,并且对功能键进行了特殊处理,但它仍然需要一个临时的char [],并且我尽量避免使用C ++代码中的那些,如果没有其他选择,则要避免一些任意的缓冲区大小。
| 归档时间: |
|
| 查看次数: |
4629 次 |
| 最近记录: |