为什么一个printf语句之后的getchar()读取的'\\ n'? [英] Why is getchar() reading '\n' after a printf statement?

查看:1026
本文介绍了为什么一个printf语句之后的getchar()读取的'\\ n'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我提示用户输入阵列的长度,初始化一个char []数组与该输入,然后提示用户键入消息进入焦炭[]数组。



我读了用户的消息的第一个字符用的getchar()



然而,的getchar()读的是新线逃逸的'\\ n'正在读任何用户输入之前。它似乎越来越的'\\ n'从previous 的printf ,提示用户声明...




下面是相关code:


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



推荐答案

当你输入号码,然后按Enter键,数字和字符被放置在输入缓冲区中,他们分别是:

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 entered number and
  • The newline character(\n).

数字变由 scanf函数消耗,但换行保留在输入缓冲区,这是由读的getchar()

The number gets consumed by the scanf but the newline remains in the input buffer, which is read by getchar().

您需要使用消耗 \\ n 之前调用的getchar()

You need to consume the \n before calling getchar() by using:

scanf("%d ", &originalLen);
         ^^^

这告诉 scanf函数阅读次数和一个额外的性格,这是 \\ n

This tells scanf to read the number and an additional character, which is \n.

这篇关于为什么一个printf语句之后的getchar()读取的'\\ n'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆