循环获取getchar功能 [英] getchar functionality in a loop

查看:388
本文介绍了循环获取getchar功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

关于"getchar"的功能.我到处都读到"getchar"的作用是读取返回第一个字符输入并将其返回.因此,如果我写以下内容:

Hi all,

Regarding the functionality of "getchar". I read everywhere that what "getchar" does, is to read return the first character input and return it. So if I write the following:

char ch;
ch=getchar();
printf("%c",ch);


...并提供"asdf qwer"作为输入,然后按"Enter",我将看到在打印"ch"时,它将返回输入序列的第一个字符("a"),这很有意义. />
但是,如果我写以下内容:


... and provide "asdf qwer" as input and press "Enter", I will see that when "ch" is printed, it will return the first character of the input sequence ("a"), which makes sense.

However, if I write the following:

char ch;

ch=getchar();

while (ch!=EOF)
{
    printf("c",ch);
    ch=getchar();
}


...并提供任何字符序列作为输入(例如,"asdf qwer"),每当我按"Enter"键时,"printf"都会打印所提供的整个字符序列("asdf qwer"),而不仅仅是第一个字符(一个").如果"getchar"应该读取并返回第一个字符输入,那么逻辑上的结论不是,如果此过程是反复进行的(直到在上述情况下我按Ctrl + z),它将返回字符序列输入的第一个字母,而不是整个序列?问题是:为什么会这样?

预先谢谢您.


...and provide whatever sequence of characters as input (e.g "asdf qwer"), whenever I press "Enter" the "printf" prints the whole sequence of characters provided ("asdf qwer") and not just the first character ("a"). If "getchar" is supposed to read and return the first character input, wouldn''t the logical conclusion be that, if this process is done iteratively (until I press Ctrl+z in the afforementioned case), it would return the first letter of the character sequence input and NOT the whole sequence? Question is: why is this happening?

Thank you in advance.

推荐答案

getchar返回 剩余 序列的第一个字符.某些流(例如标准输入)无法倒回,因此,当您阅读字符时,就这样-它已经一去不复返了.您不能撤消用户并让他从头开始输入它!
getchar returns the first character of the remaining sequence. Some streams - the standard input for example - cannot be rewound, so when you read a character, that''s it - it''s gone for good. You can''t undo the user and get him to retype it from the start!


首先,您的代码包含两个错误:

1. getchar不返回char ,而是返回int.这很重要,因为EOF通常定义为-1,否则无法将其与字符0xff区分开.

2.在printf语句中,您可能表示:

First of, your code contains two mistakes:

1. getchar does not return a char but an int. This is important, because EOF is normally defined as -1, which otherwise could not be distinguished from the character 0xff.

2. in the printf statement you probably meant:

printf("%c",ch);



现在,所有解决的问题,回到您的问题.当然,getchar不仅返回stdin流的第一个字符,而且还将其从流中删除.因此,下次调用getchar将返回字符.

作为练习,尝试想象一下getchar如果不从流中删除字符的话会多么有用.



Now, all that fixed, back to your question. Of course, getchar does not only return the first character of the stdin stream, but also removes it from the stream. Hence to next call of getchar will return the character.

As an exercise, try to imagine how useful getchar would be if it didn''t remove the character from the stream.


这篇关于循环获取getchar功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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