Reputation: 2748
I'm prompting the user to enter the length of an array, initializing a char[] array with this input, and then prompting the user to type a message to enter into the char[] array.
I'm reading the first character of the user's message with getchar()
.
However, getchar()
is reading the new-line escape '\n'
before it is reading any user input. It seems to be getting '\n'
from the previous printf
statement that prompts the user...
Here is the relevant code:
#include <stdio.h>
int main(void) {
int len = 0,
originalLen = 0;
printf("\n\nWhat is the length of the array? ");
scanf("%d", &originalLen);
char str[originalLen]; // intitializing the array
printf("Enter a message to enter into the array: ");
char target = getchar();
str[len] = target;
// why is getchar() reading '\n'?
if (target == '\n') {
printf("\n...what happened?\n");
}
return 0;
} // end of main
Upvotes: 3
Views: 6503
Reputation: 3483
You can use getchar
in a loop to flush out stdin before reading the next character.
while((target = getchar()) != '\n' && target != EOF)
Upvotes: 3
Reputation: 206546
When you enter the number and hit the ENTER key, a number and a character are placed in the input buffer, they are namely:
\n
). The number gets consumed by the scanf
but the newline remains in the input buffer, which is read by getchar()
.
You need to consume the \n
before calling getchar()
by using:
scanf("%d ", &originalLen);
^^^
This tells scanf
to read the number and an additional character, which is \n
.
Upvotes: 2
Reputation: 409196
It's because the previous scanf
does not read the newline after the number.
This can be solved two ways:
getchar
to read itscanf
format (e.g. scanf("%d ", ...)
)Upvotes: 4