handling multiple lines of strings in c

I want to take these as input

3
abc def
deg fgh
ghdfete fdgtr dhjgg

The output should be

abc def
deg fgh
ghdfete fdgtr dhjgg

The code that I have written

#include <stdio.h>
int main(){
        int t;
        scanf("%d",&t);
        char a[100];
        while(scanf("%[^\n]%*c",a) == 1){
            printf("%s\n",a);
            --t;
            if(t == 0)
                break;
        }
        return 0;
}

isn’t printing anything. Please help.

I got it You are checking for new line character before input thats why it is not printing anything.
Try this:

    #include <string.h>
    #include <stdio.h>
    int main()
    {
    	int t;
    	scanf("%d",&t);
    	while(t--)
    	{
    		char s[1000];
    		scanf("%*c%[^\n]", s);
    		printf("%s\n", s);
    		
    	}
    }

Hope this will help :smiley:

use gets(a) to take the string input

#include<stdio.h>
#include<string.h>
main()
{
int tc;
scanf("%d",&tc);
while(tc–)
{
char a[25];
fflush(stdin);
gets(a);
puts(a);
}
}
I used this code to implement this…It is working completely fine.

main()
{
	int tc;
	scanf("%d",&tc);
	while(tc--)
	{
		char a[25];
		fflush(stdin);
		gets(a);
		puts(a);
	}
}

Just corrected the view.

I used the codechef ide…it isn’t printing anything.

gets(a) won’t work.

Scanf gives -1 if it does end at last. thats why you can give

while(scanf("%[^\n]%*c",a) != EOF))

getting blank output in this case

why not???

while(scanf("%[^\t]",a) == 1) try this

it’s printing but not the correct o/p

while(scanf("%[^\t]",a) == 1) is working but it takes all 3 lines as a single string. I want to process line by line.

because scanf() u used for t. After entering value of t at console u will hit enter so that ‘\n’(new line character will be taken by proceeding scanf()) and eventually will come out without reading any input.

so make first scanf("%d ",&t); // add trailing whitespace to consume whitespace

Check now @rajarshi_iitm

but the input is this format. I can’t add a trailing whitespace after t

Have you executed this code or not

There should be a space in scanf like scanf("%d ",&tc) otherwise it won’t work correctly.