Search code examples
cinputgetchar

C, can not read input


#include <stdio.h>
#include <stdlib.h>

int main()
{

   int i,j;//count
   int c;//for EOF test
   int menu;
   unsigned int firstSize = 12811;
   unsigned int lastSize;
   char * text=malloc(firstSize);

   if(text == NULL){
        printf("\n Error. no Allocation.");
        exit(-1);
   }
printf("\n for input 1e,for autoinput press 2.");
scanf("%d",&menu);


if(menu==1){
   printf("enter text..");

   c = EOF;
   i = 0;
   lastSize = firstSize;

    while (( c = getchar() ) != '\n' && c != EOF)
    {
        text[i++]=(char)c;

        //if i reached maximize size then realloc size
        if(i == lastSize)
        {
                        lastSize = i+firstSize;
            text = realloc(text, lastSize);
        }
    }

This is the part of code which is where the problem lies.

Output when I type 1 for the scanf is:

for input 1e,for autoinput press 2.
1
enter text..

It does not let me to give input for the getchar().

But when I delete scanf for menu and use menu=1;, I can easily give input for the getchar() and it gives me output correctly:

printf("\n for input 1e,for autoinput press 2.");
scanf("%d",&menu);

instead of that

printf("\n for input 1e,for autoinput press 2.");
//scanf("%d",&menu);
menu=1;

Is it about printf scanf issues that I don't know about? In java, before taking second input, we need to put some blank. Is it like that?


Solution

  • The problem is that you press Enter after entering a number for your scanf. The number is consumed by the scanf while the newline character generated by the enter key press resides in the standard input stream(stdin).

    When the execution of the program reaches the while loop:

    while (( c = getchar() ) != '\n' && c != EOF)
    

    getchar() sees the newline character, grabs it, assigns it to c and then, the loop doesn't execute as the condition(c != '\n') is false. This is what you were unexpecting.


    You can add

    while (( c = getchar() ) != '\n' && c != EOF);
    

    anywhere between the scanf and your getchar() to clear the stdin.

    An alternative way would be to use scanf("%d%*c",&menu); as suggested by @user3121023 in the comments. %*c instructs scanf to read and discard a character. It will discard the newline character if the user had typed in a number and then pressed enter for the scanf.


    Other stuff:

    c = EOF; isn't required. Neither is the cast here: text[i++]=(char)c;. You also do not need two variables lastSize and firstSize. You should also check the return value of realloc.