[英]Is it possible to scanf multiple times without a newline in output?
Im a beginner to c and want to make my code to ask for a command and if 's' is entered it then receives a second number:我是 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();
}
I want to get a result of: Command: s2
我想得到一个结果:
Command: s2
However I get receive:但是我收到:
Command: s
2
I tried using getchar()
and fflush(stdnin)
but it didn't work.我尝试使用
getchar()
和fflush(stdnin)
但它不起作用。 I have also attempted fgets()
and didn't make any progress.我也尝试过
fgets()
并没有取得任何进展。
Edit:编辑:
Function get_char_input()
Function
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;
}
Note: command
is a char
variable with the max length of 16.注意:
command
是一个char
变量,最大长度为 16。
From the following:从以下:
printf("n - new order, s# - select order #, x - exit\n");
get_char_input(command, "Command: ", MAX_COMMAND_LENGTH);
one 'presumes' that command
is a multi-character buffer, and you prompt "s#" for entry of "s207" (for example).一个“假定”该
command
是一个多字符缓冲区,并且您提示“s#”输入“s207”(例如)。
This would do what you seem to want:这会做你似乎想要的:
if (command[0] == 's') {
the_pizzeria->selected_order = atoi( command + 1 );
You may want to add validation that the number returned is sensible.您可能需要添加验证以确认返回的数字是合理的。 It may often be 0.
它可能经常为 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.