2

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

char newline
scanf(" %s %s%c", out, in, &newline);
if(newline != '\n'){
  error();
}
Jono
  • 223
  • 2
  • 3
  • 10
  • 2
    Be careful. `out` and `in` need to have enough space to hold whatever the user types. You should probably use `%ns` where `n` is the size of the buffer pointed to by `out` or `in` `-1`. So, if your buffer is 12 bytes long, `%11s`. – nmichaels May 12 '11 at 15:39
  • i have char in[20] char out[20] , and thanks, "%20s %20x" – Jono May 12 '11 at 15:42
  • Change your buffers to 21 then. Whan dealing with strings in C always add 1 to be sure. – hugomg May 12 '11 at 16:09
  • 3
    @missingno: the problem is knowing where and when to add the one. If the one was added to the 20 in the format string (`%21s`), that would be bad; adding it to the variable definition would be OK. There isn't a simple rule of thumb; you have to know why and therefore when and where to add the one. – Jonathan Leffler May 12 '11 at 17:05

3 Answers3

3

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

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.

Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111
1

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.

Community
  • 1
  • 1
karlphillip
  • 92,053
  • 36
  • 243
  • 426