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