Hi,
I am required to first read a number, n and then n lines of string. The strings can contain leading spaces which has to be preserved:

2
" hello world"
...

using

scanf("%d", &n);
for (int i = 0;i < n;i++)
{
         scanf(" [^\n]", message);
         ....
         printf("Case #%d: %d\n",case_count, count);
}

ignores the leading space.

while doing

scanf("%d", &n);
for (int i = 0;i < n;i++)
{
         scanf("[^\n]", message);
         ....
         printf("Case #%d: %d\n",case_count, count);
         case_count++;
}

gives peculiar result. As soon as 2 is entered it shows the result:
Case #1: 0
Case #2: 0
without waiting to take " hello world"

ie bypasses the computation. As the computation excludes '\n' and '\r' characters hence I suppose it takes '\n' as string 1 and '\r' as string 2 and therefore the count is not updated.

Using gets and fgets does not help either. So now how can this problem be solved elegantly where I can take both the integer and back-to-back strings without any hassle. Is there any smart function which can take care of this (ie ignores new line and includes leading space characters)?

Thankse.

Recommended Answers

All 2 Replies

If fgets() doesn't work, I can only think of reading a character at a time..

But, you should see this about scanf() and strings.

fgets() would work perfectly well, IF you used it to read the first integer as well.

fgets( buff, sizeof buff, stdin );
sscanf( buff, "%d", &n );

Then fgets() inside the loop will preserve everything the user types in, and you can do what you want.

If you mix and match your input methods, then a disaster is all but certain (as in this case).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.