简体   繁体   English

用scanf查找C中的字符串和数字

[英]scanf for string and number in C

I've been trying to use scanf() for reading string and integer. 我一直在尝试使用scanf()读取字符串和整数。 It works fine, but I am unable to check if the input is given correctly. 它工作正常,但是我无法检查输入是否正确。

char command[6];
int cmd_num;

scanf("%5s %d", command, &cmd_num);

It works fine for reading the right input, I am able to check if the string is right by strcmp . 对于读取正确的输入,它工作正常,我可以通过strcmp检查字符串是否正确 I tried to check the number by the function isdigit() , but it cannot check correctly, I guess because of whitespaces, but I am not sure exactly how it works. 我试图通过isdigit()函数检查数字,但是由于空格,我无法正确检查数字,但是我不确定它是如何工作的。

I tried to google this, I played around with [^\\n] but still it doesn't work. 我尝试用Google搜索它,我玩过[^ \\ n],但仍然不起作用。 Could anyone enlighten me how scanf exactly works please? 任何人都可以启发我scanf的工作原理吗?

I think solution would be if I exactly could tell scanf what to read ->string(space)integer. 我认为解决方案是,如果我能确切告诉scanf读什么-> string(space)integer。 Is it possible to acquire this with regular expressions or any other way? 是否可以使用正则表达式或任何其他方式来获取它?

What I need basically is to scanf read the line recognize the string and then to check if there is a number after it too. 我基本上需要的是scanf读取该行以识别字符串,然后检查其后是否也有数字。

Another question is, I need to read the input for as long as the user is giving it, I tried to use getchar for while loop, to repeat as long as the char is not '\\n' but this closes the loop right in the beginning, but if I give it EOF condition it never ends even with multiple newlines. 另一个问题是,只要用户提供输入,我就需要读取输入,我尝试将getchar用于while循环,只要char不是'\\ n',就重复一次,但这会在开始,但是如果我给它提供EOF条件,即使有多个换行符,它也永远不会结束。 I guess it could be limited by the scanf too, but I am not sure exactly how, threads on this forum couldn't give me the answer for it. 我想它也可能受scanf的限制,但是我不确定到底是怎么回事,这个论坛上的线程无法给我答案。

This will not procced: 这不会进行:

while ( ( c = getchar() ) != '\n')
{
 //code
}

This will proceed no matter of newlines: 无论换行符如何,都将继续进行:

while ( (c = getchar() ) != EOF )
{
 //code
}

You don't check if a number is a number, and isdigit() is used to check if an ascii value is a number between 0 and 9 . 您无需检查数字是否为数字,而isdigit()用于检查ascii值是否为09之间的数字。

To check that scanf() succeeded and the input is correct, thus the value of cmd_num is correct and is an integer read from the input, you have to check the return value of scanf() . 要检查scanf()成功并且输入正确,因此cmd_num的值正确,并且是从输入中读取的整数,您必须检查scanf()的返回值。

It returns, the number of matched format specifiers. 它返回匹配格式说明符的数量。 You have two of them so 你有两个

if (scanf("%5s%d", command, &cmd_num) == 2) // this means it's correct
//                          ^ your code is missing the address of operator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM