如何从用户处获取一个号码
我刚刚学习 C,到目前为止,我一直在使用 javascript 和 php 等语言,但我很难将我的一些思维步骤转换为 C 的可能性。我正在编写的程序(听起来比实际要大)使用输入菜单让用户选择一个选项。选项可以是 1、2 或 3。
现在,我正在做:
int menu;
scanf("%d", &menu);
哪个效果很好。但是,输入字符串的字符会导致问题。
在 javascript 中,我只需将菜单变量与选项进行匹配:
if ( menu != 1 && menu != 2 && menu != 3 ){
menu = 4; // a switch later on will catch this.
}
但是,这在 C 中似乎不起作用。
我应该如何处理这个问题?
I'm just learning C, and having worked with languages as javascript and php up till now, i am having trouble converting some of my thinking steps to the possibilities of C. The program i am writing ( that sounds bigger than it really is ) uses an input menu that lets the user pick an option. The options can be 1, 2 or 3.
Now, i'm doing:
int menu;
scanf("%d", &menu);
Which works fine. However, entering a character of a string will cause problems.
In javascript i'd simply match the menu variable against the options:
if ( menu != 1 && menu != 2 && menu != 3 ){
menu = 4; // a switch later on will catch this.
}
However, that does not seem to work in C.
How should i approach this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该检查错误:(
成功时,
scanf
返回您想要读取的项目数。)如何处理错误取决于您。您可以循环直到获得有效值,或者立即中止,或者将变量设置为默认值。另一种方法是使用
fgets
读取整行输入,然后尝试对其进行标记和解释,例如使用strtok
和strtol
。You should check for errors:
(On success,
scanf
returns the number of items that you wanted to read.) How you handle the error is up to you. You could loop until you have a valid value, or abort immediately, or set the variable to a default value.An alternative is to read a whole line of input with
fgets
and then attempt to tokenize and interpret that, e.g. withstrtok
andstrtol
.scanf 函数返回一个结果,即成功读取输入的计数。 (还有
%n
格式序列来获取消耗的字符数。)。所以您可以使用任一解决方案。
或者也许:
我的第二个例子对于你的情况来说并不是很有用。但有时
%n
非常有用。我故意在
%d
之前放置一个空格:C 库会跳过空格。The scanf function is returning a result, the count of successfully read inputs. (And there is also the
%n
format sequence to get the number of consumed characters.).So you could use either solutions.
or perhaps :
My second example is not really useful in your case. But sometimes
%n
is very useful.I am putting a space before the
%d
on purpose: the C library would skip spaces.