Reputation: 15
I am trying to read in words separated by white space. There are an unknown number of words and there will be multiple lines of input. I want to read in two words at a time and then compare them before moving on.
Right now the reading and comparison work well, but I have not managed to find a way to get the loop to exit once it has reached the end of file and it continues to prompt for new input.
int main() {
char entry1[256];
char entry2[256];
printf("Enter some test words: \n");
while(scanf("%257[^ \t\n]%*c", entry1)){
printf("compare 1: %s \n", entry1);
scanf("%257[^ \t\n]%*c", entry2);
printf("compare 2: %s \n", entry2);
if ((anagramCheck(entry1, entry2)) == 1)
printf("\nThese two words are anagrams.\n");
else
printf("\nThese two words are not anagrams.\n");
}
}
This is what I am trying to achieve:
A sample input might be:
table george creative reactive tabloid pipe
And the output would be:
compare 1: table
compare 2: george
These two words are not anagrams.
compare 1: creative
compare 2: reactive
These two words are anagrams.
compare 1: tabloid
compare 2: pipe
These two words are not anagrams.
Note: -I am compiling in c89. -I did not include anagramCheck since I didn't think it was relevant to my question. But I can edit and include if it happens to be.
Upvotes: 0
Views: 233
Reputation: 241671
The usual idiom would be
while (scanf("%255s%255s", entry1, entry") == 2) {
printf("Compare 1: %s\nCompare 2: %s\n", entry1, entry");
// ...
}
which will stop when it is unable to read two words. It's not clear to me what you are hoping to accomplish with that much more complicated scanf pattern which you couldn't accomplish just with %s
. (I changed your 257 to 255, since that is the maximum number of characters you can fit in a 256-byte char array.)
Note that scanf
returns EOF
(normally -1) on error, and that is a true value as far as C is concerned. It is almost never a good idea to use while (scanf(...)) { ... }
, since that will cause the loop to continue on error or end-of-file.
From man scanf
on a Linux system:
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
The value
EOF
is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.EOF
is also returned if a read error occurs, in which case the error indicator for the stream is set, anderrno
is set indicate the error.
Upvotes: 1