Search code examples
cgetchar

C programming getchar()


I have two problems writing my code. The first problem I have is getting my getchar() to work if the user enters no text and just hits enter. I need to print an error if they do so and prompt the user to reenter the text in a loop until they do enter text. Is there any way to do so because everything I have tried has failed. Here is the code I have for that section:

printf("Enter a text message: ");
while((c=getchar()) != '\n' && c != EOF)
{
        text[i]= c;
        i++;
}

I am new to C so I am limited on ideas to fix my dilemma. As you can see I am setting the input equal to an array. This leads to my second problem, I need to limit the input to no more than 100 characters. But, instead of giving the user an error I need to just chop off the extra characters and just read the first 100.


Solution

  • The simplest solution to your problem is to use fgets. We can give limit to the input so that it doesn't read the extra characters after the given limit.

    Refer this sample code. Here I am printing the string if the user is not pressing Enter key:

    #include <stdio.h>
    
    int main() 
    {
        char str[100];
        fgets(str, 100, stdin);
        if(str[0] != '\n')
        {
            puts(str);
        }
        return 0;
    }