Reputation: 483
I've started learning how to use strings, but I'm a little bit confused about the whole concept. I'm trying to read word by word from a file that contains strings.
Here is the file:
Row, row, row your boat,
Gently down the stream.
Merrily, merrily, merrily, merrily,
Life is but a dream.
My approach was to use
char hold[25];
// Statement
while(fscanf(fpRow, "%s", hold) != EOF)
printf("%s %d\n", hold, strlen(hold));
So my task is to read each string and exclude all the , and . in the file. To do so the approach would be to use %[^,.] instead of %s correct? But when I tried this approach my string only wants to read the first word of the file and the loop never exits. Can someone explain to me what I'm doing wrong? Plus, if it's not too much to ask for what's the significance between fscanf and fgets? Thanks
while(fscanf(fpRow, "%24[^,.\n ]", hold) != EOF)
{
fscanf(fpRow, "%*c", hold);
printf("%s %d\n", hold, strlen(hold));
}
Upvotes: 2
Views: 181
Reputation: 490328
Yes, %[^,. ]
should work -- but keep in mind that when you do that, it will stop reading when it encounters any of those characters. You then need to read that character from the input buffer, before trying to read another word.
Also note that when you use either %s
or %[...]
, you want to specify the length of the buffer, or you end up with something essentially like gets
, where the wrong input from the user can/will cause buffer overflow.
Upvotes: 4