I am experimenting with the getchar()
function. Can someone please explain why every time I finish an input line with a space and then press Enter, the input window skips a line and then I have to press Enter again for the code to proceed.
#include <stdio.h>
#include <ctype.h>
#define MAX_SIZE 6 //+1 space for the 0
int main()
{
char array[MAX_SIZE] = { 0 };
char ch = 0;
while (1)
{
int i = 0;
while ((ch = getchar()) != EOF
&& ch != '\n'
// && ch != ' '
&& i < MAX_SIZE - 1)
{
if (islower(ch))
ch = toupper(ch);
else if (isupper(ch))
ch = tolower(ch);
while (ch == ' ')
ch = getchar();
array[i++] = ch;
}
array[i] = '\0';
while (ch != '\n' && ch != EOF)
ch = getchar();
printf("%s\n", array);
}
return 0;
}
Your code has:
while(ch == ' ')
ch = getchar();
If ch
is the space that was at the end of a line, the next character in the stream is a new-line character, so that sets ch
to '\n'
. Then the containing loop continues with the test in the while
:
(ch = getchar()) != EOF
&& ch != '\n'
&& i < MAX_SIZE - 1)
Since the program already read the new-line character, that getchar
seeks to read the first character of the next line. That is not in the stream buffer yet, so the computer has to read from the terminal to get it. Hence you must enter more input before the loop continues.
If you merely want to omit spaces from the output, simply do not add them to the array. Change array[i++] = ch;
to if (ch != ' ') array[i++] = ch;
and remove the while(ch == ' ')
loop.