Reading and printing strings in C

209 views Asked by At

I want to scan and print two strings one after another in a loop.But I cannot do it.Only one string gets scanned and printed if i use the loop.If i try to print without the loop then the two "gets()" work properly.

#include <stdio.h>

int main()
{
int T,i,j;
char name1[100];
char name2[100];
scanf("%d",&T);
for(i=0; i<T; i++)
{
    printf("Case %d: ",i+1);
    //scanf("%[^\n]s",name1);        
    gets(name1);
    /*for(j=0; j<strlen(name1); j++)
    {
        printf("%c",name1[j]);
    }*/
    puts(name1);
    //scanf("%[^\n]s",name2);
    gets(name2);
    /*for(j=0; j<strlen(name2); j++)
    {
        printf("%c",name2[j]);
    }*/
    puts(name2);
}
}
3

There are 3 answers

5
Utsav T On BEST ANSWER

Here you go. Use fflush(stdin). It will take two inputs and print them one after the another.

#include<stdio.h>

int main()
{
int T,i,j;
char name1[100];
char name2[100];
scanf("%d",&T);
for(i=0; i<T; i++)
{
    printf("Case %d: ",i+1);
    fflush(stdin);
    gets(name1);

    gets(name2);

    puts(name1);

    puts(name2);
}
return 0;
}

Edit: As suggested in the comment below, using gets() is not advisable if you do not know the number of characters you wish to read.

0
ZioByte On

You do not terminate your prints. stdout is buffered. Print is only performed after a "\n" or explicit flush. try something around the lines:

#include <stdio.h>

int main()
{
    int T,i,j;
    char name1[100];
    char name2[100];
    scanf("%d",&T);
    for(i=0; i<T; i++)
    {
#ifdef BAD_CODE
        printf("Case %d: ",i+1);
        gets(name1);
        puts(name1);
        gets(name2);
        puts(name2);
        putchar("\n");
#else //better code
        fgets(name1, sizeof(name1)-1, stdin);
        fgets(name2, sizeof(name2)-1, stdin);
        printf("Case %d: '%s' '%s'\n",i+1, name1, name2);
#endif
    }
}
0
Prosen Ghosh On

After taking testcase from the user, next line gets() function will take the '\n' you have to ignore the scenario.

Here's a tricky solution of this problem. Just use '\n' after %d in scanf function. scanf("%d\n",&T);

#include <stdio.h>

int main(void) {
    char s1[100],s2[100];
    int i,T;
    scanf("%d\n",&T);
    for(i = 0; i < T; i++){
        printf("Case %d: ",i+1);
        gets(s1);
        puts(s1);
        gets(s2);
        puts(s2);
    }
    return 0;
}