困惑的get​​char和scanf [英] confused about getchar and scanf

查看:156
本文介绍了困惑的get​​char和scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑的getchar的使用() scanf()的。什么是这两者之间有什么区别?

I'm really confused about the usage of getchar() and scanf(). What's the difference between these two?

我知道 scanf()的 [家庭]从用户[或文件]度日字符的字符并将其保存到一个变量,但它这样做立即或以后pressing东西(输入)?

I know that scanf() [and family] get a character by character from the user [or file] and save it into a variable, but does it do that immediately or after pressing something (Enter)?

和我真的不明白这一点code,我看到了code多件使用的getchar(),他们都让你键入任何你想在屏幕上,没有任何反应发生,但是当你preSS 输入它退出。

and I don't really understand this code, I saw many pieces of code using getchar() and they all let you type whatever you want on the screen and no response happen, but when you press enter it quits.

int j, ch;

printf("please enter a number : \n");

while (scanf("%i", &j) != 1) {
    while((ch = getchar()) != '\n') ;
    printf("enter an integer: ");
}

下面这个code我不能使用 scanf()的度日字符的字符并对其进行测试?此外,这是什么意思行?

Here in this code can't I use scanf() to get a character by character and test it? Also, what does this line mean?

scanf("%i", &j) != 1

因为当我pressed 1当我pressed 2不会有什么不同?这是什么片呢?

because when I pressed 1 it doesn't differ when I pressed 2? what does this piece do?

而当这条线要发生的事?

and when this line is gonna happen?

printf("enter an integer: ");

,因为它永远不会发生。

because it never happens.

推荐答案

好了, scanf函数是一种多用途的实用功能,可以读取多种类型的数据的基础上,格式字符串,而的getchar()只读取一个字符。

Well, scanf is a versatile utility function which can read many types of data, based on the format string, while getchar() only reads one character.

基本上,

char someCharacter = getchar();

等同于

char someCharacter;
scanf("%c", &someCharacter);

我不是100%肯定,但如果你只需要读取一个字符,的getchar()可能是便宜比 scanf函数( ),作为处理格式字符串不存在的开销(这个可以指望的东西,如果你在一个巨大的阅读许多字符,如for循环)。

I am not 100% sure, but if you only need to read one character, getchar() might be 'cheaper' than scanf(), as the overhead of processing the format string does not exist (this could count to something if you read many characters, like in a huge for loop).

对于第二个问题。

这code:

scanf("%i", &j) != 1

意味着你要 scanf函数来读取变量'J'的整数。如果成功地读出,即,在流中的下一个输入的实际上是的整数, scanf的返回1​​,因为它正确地读出,并分配1整数。

means you want scanf to read an integer in the variable 'j'. If read successfully, that is, the next input in the stream actually is an integer, scanf will return 1, as it correctly read and assigned 1 integer.

查看历史最悠久的答案 这太问题 有关 scanf函数返回值的更多细节。

See the oldest answer to this SO question for more details on scanf return values.

这篇关于困惑的get​​char和scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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