Clarification needed regarding getchar() and newline

醉酒当歌 提交于 2019-12-17 04:35:21

问题


I have a doubt regarding using getchar() to read a character input from the user.

char char1, char2;
char1 = getchar();
char2 = getchar();

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?


回答1:


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).




回答2:


I just want to know what the expected behavior is, and whether it depends on the compiler-dependent?

That's the expected behavior and not compiler-dependent.

You can use scanf to read A followed by newline, then B followed by newline. If you want to stick to getchar(), then simply give the input as AB.




回答3:


You can prevent reading newlines by explicitly testing for it. Instead of simply using

getchar():

you can use something like this

while((char1 = getchar()) == '\n');

If you're on windows you might want to test for '\r' too. So the code changes a little.

while((char1 = getchar()) == '\n' || char1 == '\r');



回答4:


add statement fflush(stdin); in between statements. look this one

ch1=getchar();

fflush(stdin);
ch2=getchar();


来源:https://stackoverflow.com/questions/12544068/clarification-needed-regarding-getchar-and-newline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!