[英]How can I distinguish between integer and character when using scanf()
I am just using the function scanf()
. 我只是在使用函数scanf()
。 The code is below: 代码如下:
scanf("%d",&a);
printf("%d",a);
When I input 1, it prints 1 like I want. 当我输入1时,它会根据需要打印1。 But even when I input 1a, it print 1 like before. 但是,即使我输入1a,它也会像以前一样打印1。 when a user inputs something not integer ((ex) 2.3,12ab,1 a) I want to show a user the warning like "input integer". 当用户输入非整数的东西((例如)2.3,12ab,1 a)时,我想向用户显示类似“输入整数”的警告。
How can I solve this problem? 我怎么解决这个问题?
Read it all into a string with fgets()
. 用fgets()
将所有内容读入字符串。
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. 如果只希望它们输入的所有内容都为单个int
,请遍历字符串并在每个字符上查找isdigit()
,然后在发现所有字符均为数字时,请调用strtod()
,如果不是,则发出错误并重新输入-提示。
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 '-' '.'
如果要从同一输入行解析多个事物,则需要使用诸如strtok()
类的字符串来解析字符串,以一次获取单个令牌,然后查看每个令牌并通过查看来确定它是否为数字如果每个字符为isdigit()
或等于'-' '.'
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. 如果是这样,请使用strtol()
或strtod()
(等等)将其解析为数字(取决于您看到的内容,int还是float / double。)否则,请将标记解析为字符串或发出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.