如何从用户那里获得一个号码 [英] How to get one number from a user

查看:34
本文介绍了如何从用户那里获得一个号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习 C,到目前为止我一直在使用 javascript 和 php 等语言,我在将我的一些思考步骤转换为 C 的可能性时遇到了麻烦.我正在编写的程序(听起来比它大确实是 ) 使用输入菜单,让用户选择一个选项.选项可以是 1、2 或 3.

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.

现在,我正在做:

int menu;
scanf("%d", &menu);

哪个工作正常.但是,输入字符串的字符会导致问题.

Which works fine. However, entering a character of a string will cause problems.

在 javascript 中,我只需将菜单变量与选项进行匹配:

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.
}

然而,这在 C 中似乎不起作用.

However, that does not seem to work in C.

我应该如何处理这个问题?

How should i approach this?

推荐答案

您应该检查错误:

int menu;
if (scanf("%d", &menu) != 1)
{
   /* error */
   /* e.g.: */  menu = 4;
}

(成功时,scanf 返回您想要读取的项目数.)如何处理错误取决于您.您可以循环直到获得有效值,或立即中止,或将变量设置为默认值.

(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.

另一种方法是使用 fgets 读取整行输入,然后尝试对其进行标记和解释,例如使用 strtokstrtol.

An alternative is to read a whole line of input with fgets and then attempt to tokenize and interpret that, e.g. with strtok and strtol.

这篇关于如何从用户那里获得一个号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆