我怎样才能整数和字符区分使用scanf函数时() [英] How can I distinguish between integer and character when using scanf()

查看:254
本文介绍了我怎样才能整数和字符区分使用scanf函数时()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是使用功能 scanf()的。在code是如下:

I am just using the function scanf(). The code is below:

scanf("%d",&a);
printf("%d",a);

当我输入1,它打印1像我想要的。
但是,即使当我输入1A,其打印1像以前一样。
当用户输入一些非整((前)2.3,12ab,1)
我想告诉用户,如输入整数。

When I input 1, it prints 1 like I want. But even when I input 1a, it print 1 like before. when a user inputs something not integer ((ex) 2.3,12ab,1 a) I want to show a user the warning like "input integer".

我该如何解决这个问题呢?

How can I solve this problem?

推荐答案

阅读这一切变成一个字符串与fgets()

Read it all into a string with fgets().

如果你只是想要的一切,他们进入是一个单一的 INT ,走串并查找 ISDIGIT()每个字符,然后当你发现这一切只不过是个数字,来电关于strtod(),如果没有,发出错误并重新提示。

If you just want everything they enter to be a single int, walk the string and look for isdigit() on each char and then when you find that it is all just digits, call strtod(), if not, emit an error and re-prompt.

如果你想多东西从相同的输入线分析,那么你需要分析的东西,如 strtok的字符串()来获得个人的令牌一次,再看看每个标记,并确定它是否是一个数字,通过查找,看是否每个字符 ISDIGIT()或等于' - ''。 之类的东西。如果是这样,解析它作为一个号与strtol()关于strtod()(ETC)(取决于您看,整数或浮点数/双。)否则,解析令牌作为一个字符串或发出错误。

If you want multiple things parse from the same input line, then you need to parse the string with something like strtok() to get individual tokens one at a time, then look at each token and determine if it is a number by looking to see if each character isdigit() or is equal to '-' '.' and suchlike. If so, parse it as a number with strtol() or strtod() (etc) (depending on what you see, int or float/double.) Otherwise, parse the token as a string or emit an error.

这篇关于我怎样才能整数和字符区分使用scanf函数时()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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