C ++ Primer第五版书(if语句)是不是正确? [英] C++ Primer fifth edtion book (if statement) is this not correct?
问题描述
#include <iostream>
int main()
{
int currVal = 0, val = 0;
if (std::cin >> currVal) {
int cnt = 1;
while (std::cin >> val) {
if (val == currVal)
++cnt;
else
{
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
currVal = val;
cnt = 1;
}
}
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
}
return 0;
}
如果我们给这个程序以下输入:
If we give this program the following input:
42 42 42 42 42 55 55 62 100 100 100
42 42 42 42 42 55 55 62 100 100 100
输出应为
42发生5次
42 occurs 5 times
55发生2次
62发生1次
100发生3次
所有这些代码都应该正常工作。对于由此带来的不便,(有一个大脑放屁)
All this code should work properly. Sorry for the inconvenience.(had a brain fart)
推荐答案
This 看起来按预期工作。
有一个很好的理由做 std :: cin>>在
提取运算符如果
语句或 while
循环的条件中的任何>>
返回您正在操作的流。因此, std :: cin>>>
There is a very good reason to do std::cin >> whatever
in the condition of an if
statement or while
loop. The extraction operator >>
returns the stream that you're operating on. So the value of the std::cin >> whatever
expression is std::cin
itself.
一个流,例如 c bool
,以检查流是否处于有效状态。请考虑:
A stream, such as std::cin
, can be converted to bool
for the sake of checking whether the stream is in a valid state. Consider:
if (std::cin >> whatever)
这可以理解为从用户输入变量 whatever
,然后检查输入是否有效。
This can be understood as taking input from the user into the variable whatever
and then checking if the input was valid or not. If not, the if
block will not execute.
同样地,
while (std::cin >> whatever)
这将循环,从用户每次的输入,直到用户输入无效的东西。
This will loop, taking input from the user each time, until the user enters something invalid.
什么是无效的输入?如果在上面的例子中无论是
int
,并且用户输入文本 blah
,这将失败,因为它不是有效的整数。
What is an invalid input? Well if whatever
in the above examples was an int
, and the user entered the text blah
, this would fail because it's not a valid integer.
这篇关于C ++ Primer第五版书(if语句)是不是正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!