Loop through user input with getchar

mysql lover picture mysql lover · Jun 19, 2015 · Viewed 10.1k times · Source

I have written a small script to detect the full value from the user input with the getchar() function in C. As getchar() only returns the first character i tried to loop through it... The code I have tried myself is:

#include <stdio.h>

int main()
{
    char a = getchar();
    int b = strlen(a);

    for(i=0; i<b; i++) {
        printf("%c", a[i]);
    }
    return 0;
}

But this code does not give me the full value of the user input.

Answer

vinayawsm picture vinayawsm · Jun 19, 2015

You can do looping part this way

int c;
while((c = getchar()) != '\n' && c != EOF)
{
    printf("%c", c);
}