问题描述
我有一个关于使用疑问的getchar()
来读取用户输入的字符。
I have a doubt regarding using getchar()
to read a character input from the user.
char char1, char2;
char1 = getchar();
char2 = getchar();
我需要获得 2
字符从用户输入。在这种情况下,如果用户输入后跟一个换行
,然后字符<$字符'A'
C $ C>'B',什么将被存储在 CHAR2
- 不会是换行字符或字符 'B'
? (我试图在$ C $个cblocks的窗户, CHAR2
实际存储换行符(但我打算它来存储字符'B'
))。我只是想知道预期的行为是什么,以及它是否是编译器相关?如果是这样,用Turbo C和MinGW之间持有什么区别 - 柜面任何人遇到过吧:)
I need to get 2
chars as inputs from the user. In this case, if the user enters the character 'A'
followed by a newline
, and then the character 'B'
, what will be stored in char2
- will it be the newline character or the character 'B'
? (I tried it on codeblocks on windows, and char2
actually stores the newline character (but I intended it to store the character 'B'
)). I just want to know what the expected behavior is, and whether it is compiler-dependent? If so, what differences hold between turbo C and mingW - incase anyone has encountered it before :)
推荐答案
是的,你要消耗每个输入后换行:
Yes, you have to consume newlines after each input:
char1 = getchar();
getchar(); // To consume `\n`
char2 = getchar();
getchar(); // To consume `\n`
这是不是编译器相关。这是所有的平台真正的,因为会在每个输入行的末尾回车(虽然实际换行可以跨平台有所不同)。
This is not compiler-dependent. This is true for all platforms as there'll be carriage return at the end of each input line (Although the actual line feed may vary across platforms).
这篇关于需要澄清有关的getchar()和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!