Search code examples
cinputgetchar

Trouble with getchar() in c


I have a c program and I ask for the user input twice during my program. The first time the input function (my own) worked perfectly, but the second time the getchar() function seemingly doesn't run. I have looked into the problem myself and I found something related to trailing characters, but I'm still confused on my problem. I've tried to create a second function where the function keeps asking for input if the input given is a \n, and I've also tried using an extra getchar() function to get rid of the stored character in the input stream (I still don't fully understand this either). I've also tried other things, but they were involving my larger structures but not the getchar() function itself

My input function:

int getInput(char s[])
{
  char c;
  int i = 0;
  while((c = getchar()) != EOF){
    s[i] = c;
    i++;
  }
  return i;
}

My main function:

main()
{
  printf("Enter a string to convert: \n");
  char s[1000];
  int len = getInput(s);
  char t[1000];
  printf("Press 1 to convert from escape to real, or 2 to convert from real to escape: ");
  char a[1];
  getInput(a);
  printf("%d\n", a[0]);
  if(a[0] == '1') {
    real(s, t, len);
  } else if (a[0] == '2') {
    escape(s, t, len);
  } else {
    printf("\nRestart the program and enter a 1 or a 2\n");
    exit(0);
  }
  printf("\n%s\n", t);
}

Thank you


Solution

  • Actually your first getInput doesn't work as you would expect it to worked. Indeed this is where your program gets stuck because getchar still waits for an input.

    When writing the input in your terminal and pressing Enter you fill the buffer of stdin and then you empty that buffer with your getchar.
    Now let's say you write hello and then press Enter, so now you buffer is filled with hello\n (because when you press Enter, the newline is also put into the buffer).
    Now your getchar will consume each and every letter until there is nothing left in your buffer. At this point I guess you though that getchar would return an EOF because there is nothing left to read but do not forget that when there is nothing to read getchar just waits for you to input something just like scanf.

    So now you're trapped in a loop, you fill your input, it gets read, then you have to fill another input and you never leave the loop.

    A solution would be to change your loop condition to stop when getchar returns the \n (because remember it also gets added into the buffer), so at this point the buffer would be empty, your string would be correct and your function would return.