0
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void) {
    char a[1001];
    int t,i;
    scanf("%d",&t);

    while(t--)
    {
        fflush(stdin);
        gets(a);
        printf("%d\t",t);
        puts(a);

    }
    return 0;
}

Input:

2 
die another day.
i'm batman.

Ouput:

1   
0   die another day.

Expected Output:

1    die another day.
0    i'm batman.

Anyone please help how to accept more than one string without any bugs. I am able to see after entering 2 my gets is taking newline as first string and later second string properly. Thanks in advance

2
  • 2
    Technically fflush(stdin) is undefined behavior. It's not supported on all systems and platforms. Commented Apr 17, 2014 at 14:17
  • Any idea to make the program work on almost compilers properly?Including online compilers. Commented Apr 17, 2014 at 14:18

2 Answers 2

2

Stop using scanf() of stdin to read input. Never call fflush(stdin); either, but if you stop using scanf() you will no longer want to.

Read whole lines using fgets() into suitably-sized string buffers, then parse what you got. One good function for parsing a string is sscanf() which is just like scanf() except it reads from a string instead.

This will be much easier, less annoying, and just generally better. Oh, and of course never use gets().

Something like this (untested):

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  char line[256];

  if(fgets(line, sizeof line, stdin))
  {
    int count;
    if(sscanf(line, "%d", &count) == 1)
    {
      while(count > 0)
      {
        if(fgets(line, sizeof line, stdin))
        {
          printf("%s", line);
          --count;
        }
        else
          break;
      }
    }
  }
  return EXIT_SUCCESS;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I m a newbie can you please give a example how to use fgets()
Can you explain the flow i am not able to get the functionality of the methods mention
@tech_boy I made fgets() and sscanf() into links, so you can read the documentation to figure out exactly how those functions work.
0

Dont use fflush(stdin). use getchar() to clear the [enter] character left after scanf() as,

#include <stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void) {
    char a[1001];
    int t,i;
    scanf("%d",&t);
     getchar();
    while(t--)
    {

        gets(a);
        printf("%d\t",t);
        puts(a);

    }
    return 0;
}

it works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.