我是 c 语言的初学者,想让我的代码请求命令,如果输入“s”,则会收到第二个数字:
void get_command(char *command) {
struct pizzeria *the_pizzeria;
printf("n - new order, s# - select order #, x - exit\n");
get_char_input(command, "Command: ", MAX_COMMAND_LENGTH);
}
//....
void process_command(struct pizzeria *the_pizzeria, char *command) {
if (command[0] == 'n') {
struct order **last_next_order_field = get_last_next_order_field(the_pizzeria);
*last_next_order_field = create_order();
}
if (command[0] == 's') {
get_integer_input(&the_pizzeria->selected_order, "");
printf("\n \n");
}
}
//....
void get_integer_input(int *variable, char *prompt) {
printf(prompt);
scanf("%d", variable);
getchar();
}
我想得到以下结果:命令:s2
但是我收到:
Command: s
2
我尝试使用 getchar()
和 fflush(stdnin)
但它不起作用。我也尝试过 fgets()
但没有取得任何进展。
编辑:
函数get_char_input()
void get_char_input(char *variable, char *prompt, int length) {
printf(prompt);
fgets(variable, length, stdin);
variable[strcspn(variable, "\r\n")] = 0;
}
注意:command
是一个char
变量,最大长度为16。
最佳答案
来自以下内容:
printf("n - new order, s# - select order #, x - exit\n");
get_char_input(command, "Command: ", MAX_COMMAND_LENGTH);
一个“假设”命令
是一个多字符缓冲区,并且您提示“s#”输入“s207”(例如)。
这会做你想要的事情:
if (command[0] == 's') {
the_pizzeria->selected_order = atoi( command + 1 );
您可能需要添加验证,以确保返回的数字是合理的。它通常可能是 0。
关于c - 是否可以多次 scanf 且输出中没有换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73507358/