Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

c - Why is getchar() reading ' ' after a printf statement?


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 ' ' before it is reading any user input. It seems to be getting ' ' 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("

What 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 '
'?
    if (target == '
') {
        printf("
...what happened?
");
    }
    return 0;
} // end of main


See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because the previous scanf does not read the newline after the number.

This can be solved two ways:

  1. Use e.g. getchar to read it
  2. Add a space after the scanf format (e.g. scanf("%d ", ...))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...