简体   繁体   中英

scanf for string and number in C

I've been trying to use scanf() for reading string and integer. 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 . 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.

I tried to google this, I played around with [^\\n] but still it doesn't work. Could anyone enlighten me how scanf exactly works please?

I think solution would be if I exactly could tell scanf what to read ->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.

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. 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.

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 .

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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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