3
votes

So I have to get scanf to read in a few strings that are separated by spaces. However, I don't know beforehand how many strings I need to read it it can be anywhere from 1 to 5, but I can't seem to get scanf to stop trying to read after hitting enter in the input. I have tried doing the naive %s %s %s %s %s but as you can imagine after hitting enter after say just 1 or 2 words it still expects to read more in and then I also tried to do %s%*[^\n]%s%*[^\n]%s%*[\n]%s%*[\n]%s%*[^\n] so that it would try to stop after a new line character but that didn't work either.

So what is the best way to get scanf to be able to have some optional input sections.

Thanks.

Edit: I know about strtok and fgets I was just looking to see if there was a way to do this with scanf

2

2 Answers

6
votes

How about using fgets to read one line and then strotk / sscanf to parse it ? Then you'll be able to decide how many strings the user has entered.

2
votes

scanf doesn't enforce reading the whole format string, it aborts once it gets invalid input or no input is left.

From http://www.cplusplus.com/reference/clibrary/cstdio/scanf/:

On success, the function returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens.

The following code tells you how many arguments were read during scanf:

char s1[10], s2[11], s3[11], s4[11], s5[11];
int read = scanf("%10s %10s %10s %10s %10s", s1, s2, s3, s4, s5);
printf("Read %d strings", read);

If you enter aaa bbb ccc and hit enter, it prints 3, for aaa bbb ccc ddd it prints 4, etc.