开发者

scanf validation C

will this actually verify my users input has only two elements then a newline?

char newline
scanf(" %s %s%c", out, in, &n开发者_StackOverflow社区ewline);
if(newline != '\n'){
  error();
}


You must check the return status from scanf(); if it does not return 3, you failed the validation. Your checks will ensure that there are two 'words' (possibly preceded by some space). You won't be allowed trailing space after the second word. Note that you might need to 'eat' the rest of the line if the validation fails - you won't if you have a newline in newline.


Yes, that will work. But only if the input matches exactly: word word<enter>.

If the user types anything different from that format, for instance, a space between the 2nd word and enter, your logic will fail.

char newline;
char out[50];
char in[50];
scanf("%s %s%c", out, in, &newline);
if(newline != '\n')
{
  printf("error!");
}

Also, scanf shouldn't be used to read from the input like that. Consider using fgets to read the input and strtok to parse the data.


No! scanf will work incorrect if there are some whitespace character between second string and newline. use getc() for that:

scanf("%s%s", buf1, buf2);
char newline = 0;
while((newline = getc()) == ' '  || newline == '\t');
if(newline != '\n'){
  error();
}

Edit:

Adding case for trailing whitespaces.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜