为什么一个字符在此之后的getchar()循环停止已进入? [英] Why does this getchar() loop stop after one character has been entered?

查看:168
本文介绍了为什么一个字符在此之后的getchar()循环停止已进入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main() {
    char read = ' ';

    while ((read = getchar()) != '\n') {
        putchar(read);
    }

    return 0;
}

我的输入˚F(后跟一个输入,当然)。我期待的getchar(),要求再次输入,而是程序终止。怎么来的?我该如何解决这个问题?

My input is f (followed by an enter, of course). I expect getchar() to ask for input again, but instead the program is terminated. How come? How can I fix this?

推荐答案

终端有时会有点混乱。您应该将程序更改为:

The Terminal can sometimes be a little bit confusing. You should change your program to:

#include <stdio.h>

int main() {
    int read;
    while ((read = getchar()) != EOF) {
        putchar(read);
    }
    return 0;
}

这将读到的getchar读取EOF(极本宏展开-1的时间)从终端。 getchar函数返回一个int,所以你应该让你的变量读成一个整数,所以你可以检查EOF。你可以从你的终端在Linux上发送一个EOF用^ D,我认为与^ Z窗口(?)。

This will read until getchar reads EOF (most of the time this macro expands to -1) from the terminal. getchar returns an int so you should make your variable 'read' into an integer, so you can check for EOF. You can send an EOF from your terminal on Linux with ^D and I think on windows with ^Z (?).

要解释一下会发生什么。在程序中的前pression

To explain a little bit what happens. In your program the expression

(read = getchar()) !='\n'

,因为没有的'\\ n'是从缓存器读出将是只要真。问题是,得到缓冲到您的程序,你必须按下回车键对应的'\\ n'。
当你的程序在终端调用下面的步骤发生:

will be true as long as no '\n' is read from the buffer. The problem is, to get the buffer to your program, you have to hit enter which corresponds to '\n'. The following steps happen when your program is invoked in the terminal:

~$\a.out

这将启动程序

(empty line)                    

的getchar()取得一个系统调用来获得来自终端的输入端和终端接管

getchar() made a system call to get an input from the terminal and the terminal takes over

f                   

您做在终端的输入。该f被写入缓冲器和回显在终端上,你的程序有没有关于角色的想法呢。

you made an input in the terminal. The 'f' is written into the buffer and echoed back on the terminal, your program has no idea about the character yet.

f
f~$                 

您按下回车键。您的缓冲区现在包含'F \\ N'。在'输入'也标志着到终端,它应该返回给程序。你的编程'
读取缓冲区,会发现f和把它搬上银幕,然后找到一个'\\ n'以及immediatley停止循环,结束程序。

You hit enter. Your buffer contains now 'f\n'. The 'enter' also signals to the terminal, that it should return to your program. Your progam reads the buffer and will find the f and put it onto the screen and then find an '\n' and immediatley stop the loop and end your program.

这将是最终端的标准行为。你可以改变这种行为,但是这将取决于您的操作系统。

This would be standard behaviour of most terminals. You can change this behaviour, but that would depend on your OS.

这篇关于为什么一个字符在此之后的getchar()循环停止已进入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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