我正在做一个使用 ncurses 并用 C 语言编写的小项目。我遇到了两个关于验证输入的问题。 例如,情况 1:我想验证输入是否是指定的特定字符,例如:a 或 b 或 c。
char choice;
printw("a. New name\n");
printw("b. Edit name\n");
printw("c. Exit\n");
scanw("%c", &choice);
if (choice == 'a')
//Do something
else if(choice =='b') {
//Do something
}
else if(choice == 'c') {
exit(0);
}
情况 2:我只想验证整数范围内的输入,例如:1 到 5。
int player_number
printw("How many players ? (1 - 5): ");
scanw("%i", &player_number);
具有讽刺意味的是,我可以在 ncurses 上下文之外找到这两个问题的解决方案。另外,当程序提示用户输入时,如何使用“q”等按键退出程序。 谢谢
最佳答案
你可以尝试这样的事情。
#include <ncurses.h>
int main()
{
char choice = 0;
int player_number = -1;
initscr ( );
do {
mvprintw ( 1, 1,"a. New name");
mvprintw ( 2, 1,"b. Input number");
mvprintw ( 3, 1,"c. Exit");
mvprintw ( 4, 1," ");
if (( scanw("%c", &choice)) == 1) {//scanw succeeded
if ( ! ( choice == 'a' || choice == 'b' || choice == 'c')) {
mvprintw ( 5, 1,"invalid input, should be a, b or c");
}
else {
mvprintw ( 5, 1," ");
}
}
} while ( ! ( choice == 'c' || choice == 'b'));
mvprintw ( 5, 1," ");
if ( choice == 'b') {
do {
mvprintw ( 7, 1,"Enter number 0-9");
mvprintw ( 8, 1," ");
if (( scanw("%d", &player_number)) == 1) {//scanw succeeded
if ( player_number < 0 || player_number > 9) {
mvprintw ( 9, 1,"invalid input, should be 0-9");
}
}
else {//scanw failed
mvprintw ( 9, 1,"invalid input, should be 0-9");
}
} while ( player_number < 0 || player_number > 9);
}
endwin ( );
return 0;
}
使用 char 数组包含输入并使用 getnstr()
读取输入,可以检测到 q
输入来退出程序。对于数字输入,strtol()
用于将数组转换为 int。
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
int main()
{
char choice = 0;
char instr[128] = {0};
int player_number = -1;
initscr ( );
do {
mvprintw ( 1, 1,"a. New name");
mvprintw ( 2, 1,"b. Input number");
mvprintw ( 3, 1,"c. Exit");
mvprintw ( 4, 1," ");
if (( getnstr( instr, 1)) != ERR) {//succeeded
choice = instr[0];
if ( ! ( choice == 'a' || choice == 'b' || choice == 'c')) {
mvprintw ( 5, 1,"invalid input, should be a, b or c");
if ( choice == 'q') {//quit when q is entered
endwin ( );
return 0;
}
}
else {
mvprintw ( 5, 1," ");
}
}
} while ( ! ( choice == 'c' || choice == 'b'));
mvprintw ( 5, 1," ");
if ( choice == 'b') {
do {
mvprintw ( 7, 1,"Enter number 0-9");
mvprintw ( 8, 1," ");
if (( getnstr( instr, sizeof ( instr))) != ERR) {//succeeded
if ( instr[0] == 'q' && instr[1] == '\0') {//quit when q is entered
endwin ( );
return 0;
}
player_number = strtol ( instr, NULL, 10);
if ( player_number < 0 || player_number > 9) {
mvprintw ( 9, 1,"invalid input, should be 0-9");
}
}
else {//failed
mvprintw ( 9, 1,"invalid input, should be 0-9");
}
} while ( player_number < 0 || player_number > 9);
}
endwin ( );
return 0;
}
关于C 编程 ncurses 输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32357244/