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.

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).

This article has been dead for over six months. Start a new discussion instead.