如何从用户处获取一个号码

发布于 2024-12-25 17:48:50 字数 457 浏览 3 评论 0原文

我刚刚学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

城歌 2025-01-01 17:48:50

您应该检查错误:(

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

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

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

You should check for errors:

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

(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. with strtok and strtol.

思慕 2025-01-01 17:48:50

scanf 函数返回一个结果,即成功读取输入的计数。 (还有 %n 格式序列来获取消耗的字符数。)。

所以您可以使用任一解决方案。

if (scanf(" %d", &menu)  != 1) { 
  /* handle error */
}

或者也许:

int pos =  -1;
if (scanf(" %d %n", &menu, &pos) <=0 || pos <= 0) {
  /* handle error */
}

我的第二个例子对于你的情况来说并不是很有用。但有时 %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.

if (scanf(" %d", &menu)  != 1) { 
  /* handle error */
}

or perhaps :

int pos =  -1;
if (scanf(" %d %n", &menu, &pos) <=0 || pos <= 0) {
  /* handle error */
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文