如果 (cin) { while(cin) ..工程?

How is if (cin) { while(cin)... Works?

本文关键字:cin 工程 如果 while      更新时间:2023-10-16
int main () {
int num1, num2;
int cnt = 1;
if (cin >> num1){       
while (cin >> num2){
if (num1==num2){
++cnt;
} else {
cout << num1 << " is " << cnt << " times" << endl;
cnt = 1;
num1 = num2;
}
}
}
cout << num1 << " is " << cnt << "-times" << endl;
}

此代码接受一行数字并输出每个数字的输入次数。我不明白的是为什么会有num1=num2.删除它后,程序输出输入的第一个数字,这让我相信我不知道cin如何在循环中工作。

我现在认为的是,第一个数字进入if (cin >> num1),并且它一直坐在这里,接下来相同的数字不会覆盖整数num1。第二个和其余数字进入while (cin >> num2)每次都会覆盖它,直到有一个不同的数字,这使得else执行并输出整个时间存储在num1中的数字。

随着num1=num2,它if(cin>> num1)num1发生了变化,整个事情又重新开始了。 我说的对吗?

这也很奇怪,最后的可能肯定在第一个if身体里面,它可能不会,无论如何它都有效......

编辑1:数字1=数字2;我输入 1 1 2 2 3 3 3,作为一行,它输出

1 is 2 times
2 is 2 times
3 is 3 times. 

没有 num1=num1;

1 is 2 times
1 is 1 times
1 is 1 times
1 is 1 times
1 is 1 times
#include <iostream>
int main () {
int num1, num2;
int cnt = 1;
if (std::cin >> num1) { // if a valid integer can be extracted from cin
while (std::cin >> num2) { // do as long as valid integers are extracted from cin
if (num1 == num2) { // if the first extracted int matches the next one
++cnt; // increase the count
}
else { // if it is a different int then do some output and
std::cout << num1 << " is " << cnt << " timesn";
cnt = 1; // reset the counter and
num1 = num2; // remember the new extracted number for
// the next iteration of the while-loop
// since only num2 will be read again from cin
}
}
}
std::cout << num1 << " is " << cnt << "-timesn";
}

由于如果没有有效的输入,main()的最后一行毫无意义,我主张提前退出:

#include <cstdlib>
#include <iostream>
int main () {
// ...
if (!( std::cin >> num1 ))
return EXIT_FAILURE;
while (std::cin >> num2) {
if (num1 == num2) {
//  ...

它还减少了缩进级别,从而提高了可读性。

cin >> num1尝试将标准输入中的数字读取到num1变量中。如果成功,将执行if的正文。否则(例如,如果用户输入了数字以外的内容或立即按 Ctrl-d/Ctrl-z(,我们直接跳转到if后的代码。这恰好发生一次。

cin >> num2num2变量执行相同的操作,只是这次它在while内而不是if内。因此,如果输入操作成功,则 while 循环的主体将执行,然后再次执行cin >> num2,直到最终失败。

我不明白的是为什么会有num1=num2.

正如我所说,cin >> num1只执行一次(它不在任何循环中(。因此,如果您从不重新分配num1,它将始终保留输入的第一个值。但是你不希望它,你希望它包含你当前正在计算的值。这就是为什么这个任务在那里。

当 num1=num2 时,它会在 if(cin>> num1( 中改变 num1,然后整个事情重新开始。我说的对吗?

不,cin >> num1再也不会执行了。它不在循环内。只有cin >> num2被多次执行,因为该while循环的一部分。

这也很奇怪,如果身体,最后一个cout可能会确定在第一个里面,而且它可能不是,无论如何它都有效......

如果第一次输入操作失败,它将立即跳到主体外部。如果cout语句存在,则意味着即使第一个输入失败,它也将被执行。在这种情况下,num1将未初始化,因此使用它将调用未定义的行为。因此,该声明不应超出if

我理解代码的作用是计算并显示数字的连续出现次数,因此它不适用于无序列表。

也就是说,它的工作原理基本上如下:

  1. 查看流中是否有可用的数字,如果有,请将其存储在num1中。
  2. 对于以下每个数字,读取要num2的数字。
  3. 如果num1num2相同,则递增计数器。
  4. 但是,如果数字不同:输出重复计数,将计数器设置为 1,并将比较的第一个数字 (num1( 更改为新读取的数字 (num2(。

第一个如果if (cin >> num1)检查 num1 中是否有输入(当然是等待输入(,然后它才会继续循环。

然后,如果输入为空,它等待 num2 的第二个输入并进入循环。

然后,它比较两个输入。如果它们是一样的...它递增计数器。 否则,它将输出在一行中检测到相同输入的次数,然后将比较输入更改为上次输入的值并重复循环,等待输入。

因此,它会比较您一次又一次地提供相同输入的次数......

基本上,如果输入是:

5
5
5
1

输出将为"5 是 3 倍">

如果输入是

1
5
5
5

输出将为"1 是 1 倍">