I wrote this code to get familiar with getchar(). I took line
while(ch != '\n' && ch != EOF)
ch = getchar();
from a book. What is a mystery to me is that in the second while loop using getchar() leads to the program asking me for an input.
In the line
while(ch != '\n' && ch != EOF)
ch = getchar();
using getchar() does not lead to the program asking for an input. Is it because there is still information in the buffer?
My input is any line with more than the MAX_SIZE number of characters.
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 10
int main ()
{
int ch = 0,
i = 0;
char array[MAX_SIZE] = {0};
while(1)
{
i = 0;
while((ch = getchar()) != EOF && ch != '\n' && i < MAX_SIZE - 1)
{
array[i++] = ch;
}
array[i] = '\0';
while(ch != '\n' && ch != EOF)
ch = getchar();
printf("%s\n",array);
for (int i = 0; i < strlen(array) + 1; i++)
printf("[%d]%d\n",i, array[i]);
}
}
i < MAX_SIZE - 1before callinggetchar(). The answer to your first question depends on the initial value ofch, which you haven't shown.