我正在尝试使用getchar()读取整数。这是我正在使用的代码:使用getchar()读取整数
while (thisChar = getchar() != '\n') {
n = n * 10 + thisChar - '0';
}
int n
被初始化为零,并且thisChar
被声明为int
对于单位输入,n被返回为-47,这意味着为start of heading
字符值正在被阅读。我在while
表达式中分配thisChar
的方式有什么不正确吗?
我正在尝试使用getchar()读取整数。这是我正在使用的代码:使用getchar()读取整数
while (thisChar = getchar() != '\n') {
n = n * 10 + thisChar - '0';
}
int n
被初始化为零,并且thisChar
被声明为int
对于单位输入,n被返回为-47,这意味着为start of heading
字符值正在被阅读。我在while
表达式中分配thisChar
的方式有什么不正确吗?
它遗漏括号:
int thisChar;
while ((thisChar = getchar()) != '\n') {
n = n * 10 + thisChar - '0';
}
如果没有这些额外的括号,你总是分配给thisChar
比较getchar() != '\n'
的值,即始终1
或0
...
请注意,您也应该处理EOF
:
int thisChar = getchar();
while (thisChar != EOF && thisChar != '\n') {
n = n * 10 + thisChar - '0';
thisChar = getchar();
}
!=
have hi比=
运营商的优先级高。因此,表达式
while(thisChar = getchar() != '\n') {...}
将被解析为
while(thisChar = (getchar() != '\n')) {...}
和比较getchar() != '\n')
的结果将被分配到thisChar
。
你需要把子表达式thisChar = getchar()
支架
while((thisChar = getchar()) != '\n') {...}
正确,但只有一个赋值运算符,因此它的关联性无关紧要。问题是'!='具有比'='更高的优先级。 –
@KeithThompson;对不起。我现在纠正了它。 – haccks
给予好评里面。 'thisChar - '0''可以是'1 - 48',这解释了OP的'-47'为单个数字。 –
@WeatherVane如果thischar的类型为'int',那么需要使用' - '0''是什么? – roottraveller
@rkm_Hodor,因为它正在读取数字字符'0'..'9'',它们没有* value *。所以你减去''0'来得到整数范围'0..9'。在ASCII(这是常见的但并不总是使用)中,数字字符“0”,“9”具有值“48..57”。 –