[英]how to read enter input on c
This function will be called by the menu. 该功能将由菜单调用。
void exponentiation()
{
int i, result = 0, first, second;
printf("\n%s\n%s\n\n%s",
"1) Exponentiation",
"------------------",
"Enter 1st integer: ");
scanf("%d", &first);
printf("Enter 2nd integer: ");
scanf("%d", &second);
printf("%d raised to %d equals %d\n", first, second, result);
main();
}
From this function I need to read the user input, if the user input is "enter" without any integer, it should be going back to the menu which is calling the main(). 从这个函数我需要读取用户输入,如果用户输入是“enter”而没有任何整数,它应该返回到调用main()的菜单。
I already tried to get the input. 我已经尝试过输入了。 For example:
例如:
if(first == '\n')
{main();}
or 要么
if(first == 10) /**which is 10 is ASCII code for enter**/
{main()}
Both ways it didn't work at all, any suggestions? 这两种方式根本不起作用,有什么建议吗?
both ways it didn't work at all, any suggestion
两种方式根本不起作用,任何建议
The function scanf
returns the number of items it successfully scanned. 函数
scanf
返回成功扫描的项目数。 You should check its return and go back if it doesn't matches your expectations. 如果不符合您的期望,您应该检查它的返回并返回。
Also you should know %d
ignores whitespace . 你也应该知道
%d
忽略空格 。 So if the user hits return without entering an integer, scanf
simply skips over it and waits for something else. 因此,如果用户在不输入整数的情况下返回,则
scanf
只是跳过它并等待其他内容。
If you insist on not ignoring whitespace this way, you should avoid scanf
and use other input methods such as fgets
. 如果你坚持不以这种方式忽略空格,你应该避免使用
scanf
并使用其他输入方法,如fgets
。 Get input from the user line by line and use sscanf
, strtoul
and strtok
to make sense of it. 逐行从用户那里获取输入,并使用
sscanf
, strtoul
和strtok
来理解它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.