使用scanf只是为了数字,不允许使用字母或字符 [英] using scanf just for numbers, not allowing letters or characters

查看:399
本文介绍了使用scanf只是为了数字,不允许使用字母或字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void FillArray(int m[35])
{
    int i;
    for (i = 0; i <= 34; i++)
    {
        printf("Enter Mark for Element[%d] :", i);
        scanf("%d", &m[i]);
        while (m[i]<=1 || m[i]>=7)
        {
        printf("\nError! Mark should in range of (2 to 6).\n\n");
        printf("Enter Mark again for Element[%d] :", i);
        scanf("%d", &m[i]);
        }
    }
}






此代码中的
取2到6之间的nubers,但是当我输入一个坚持代码的字母时,参数我只需要使用数字意味着不允许使用字母或字符谢谢




in this code i m taking nubers between 2 - 6 but when i enter a letter sticking to code which parameter i need to just use numbers mean not allow letters or characters thank you

推荐答案

scanf 无法阻止用户输入任何内容:它只是读取用户键入的内容并尝试根据您提供的格式处理它并返回一个值,表示它是通过还是失败。

如果你需要阻止用户输入无效字符,你需要使用你的操作系统/编译器特定的函数来读取键入的每个字符并接受或者在那时拒绝它。
scanf can't prevent the user typing anything: all it does is read what the user typed and try to process it according to the format you provide and return a value which says if it passed or failed.
If you need to prevent the user typing invalid characters, you need to use your operating system / compiler specific functions to read each character as it is typed and accept or reject it at that point.


AS Griff说你需要去比scanf更低的水平。我不禁提到谷歌有多么有用。试试这个并忽略2票:



从键盘输入一个数字输入,然后将每个组件放入一个数组中 [ ^ ]
AS Griff says you need to go to a lower level than scanf. I can't help mentioning how useful Google is. Try this and ignore the 2 vote:

Rread a number input from the keyboard and then put each of its components in an array[^]


Quote:

scanf(%d,& m [i]);

scanf("%d", &m[i]);

这不正确使用 scanf :你应该经常检查它的返回值,即:

That is not the correct usage of scanf: you should always check its return value, that is:

if ( scanf("%d", &m[i]) != 1 )
{
  // handle error.
}


这篇关于使用scanf只是为了数字,不允许使用字母或字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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