`getchar()` 在哪里存储用户输入? [英] Where does `getchar()` store the user input?

查看:22
本文介绍了`getchar()` 在哪里存储用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始阅读C 编程语言" (K&R) 并且我对 getchar() 函数有疑问.

I've started reading "The C Programming Language" (K&R) and I have a doubt about the getchar() function.

例如这段代码:

#include <stdio.h>

main()
{
  int c;

  c = getchar();
  putchar(c);
  printf("
");   
}

输入 toomanychars + CTRL+D (EOF) 只打印 t.我认为这是意料之中的,因为它是引入的第一个角色.

Typing toomanychars + CTRL+D (EOF) prints just t. I think that's expected since it's the first character introduced.

然后是另一段代码:

#include <stdio.h>

main()
{
  int c;

  while((c = getchar()) != EOF) 
    putchar(c);
}

输入 toomanychars + CTRL+D (EOF) 打印 toomanychars.

Typing toomanychars + CTRL+D (EOF) prints toomanychars.

我的问题是,如果我只有一个 char 变量,为什么会发生这种情况?其余的字符存储在哪里?

My question is, why does this happens if I only have a single char variable? where are the rest of the characters stored?

感谢大家的回答,我现在开始明白了……只有一个问题:

Thanks to everyone for the answers, I start to get it now... only one catch:

第一个程序在给定 CTRL+D 时退出,而第二个程序打印整个字符串,然后等待更多的用户输入.为什么它等待另一个字符串而不像第一个那样退出?

The first program exits when given CTRL+D while the second prints the whole string and then waits for more user input. Why does it waits for another string and does not exit like the first?

推荐答案

它将输入流视为文件.就好像您打开了一个包含文本toomanychars"的文件,并一次读取或输出一个字符.

It's treating the input stream like a file. It is as if you opened a file containing the text "toomanychars" and read or outputted it one character at a time.

在第一个例子中,在没有while循环的情况下,就像你打开一个文件并读取第一个字符,然后输出它.但是,第二个示例将继续读取字符,直到它获得文件结束信号(在您的情况下为 ctrl+D),就像它从磁盘上的文件中读取一样.

In the first example, in the absence of a while loop, it's like you opened a file and read the first character, and then outputted it. However the second example will continue to read characters until it gets an end of file signal (ctrl+D in your case) just like if it were reading from a file on disk.

回复您更新的问题,您使用的是什么操作系统?我在我的 Windows XP 笔记本电脑上运行它,它运行良好.如果我按回车键,它会打印出我到目前为止的内容,换行,然后继续.(getchar() 函数在您按下 Enter 之前不会返回,此时输入缓冲区中没有任何内容被调用).当我按下 CTRL+Z(Windows 中的 EOF)时,程序终止.请注意,在 Windows 中,EOF 必须在其自己的一行上才能在命令提示符中算作 EOF.我不知道这种行为是否在 Linux 或您可能正在运行的任何系统中被模仿.

In reply to your updated question, what operating system are you using? I ran it on my Windows XP laptop and it worked fine. If I hit enter, it would print out what I had so far, make a new line, and then continue. (The getchar() function doesn't return until you press enter, which is when there is nothing in the input buffer when it's called). When I press CTRL+Z (EOF in Windows), the program terminates. Note that in Windows, the EOF must be on a line of its own to count as an EOF in the command prompt. I don't know if this behavior is mimicked in Linux, or whatever system you may be running.

这篇关于`getchar()` 在哪里存储用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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