Search code examples
cstringgetsputs

Reading and printing strings in C


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);
}
}

Solution

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