#include <iostream>
using namespace std;
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<<"ocurrs"<<cnt<<"times"<<std::endl;
currVal=val;
cnt=1;
}
}
std::cout<<currVal<<"ocurrs"<<cnt<<"times"<<std::endl;
}
return 0;
}
以上代码是c++primer中关于if语句的一段代码,在最开始的运行过程中,出现了无法将最后一组数以及其重复次数输出的问题,即while循环外的代码无法正常运行。
查询后发先,是程序在运行时没有跳出while循环,需要在数字后添加一个停止符——ctrl+z,即可跳出循环,但运行后又发现加上ctrl+z后,程序直接停止运行,并没有输出值。
后来发现程序需要编译后再运行,即“build and run”后,即可达到书上的效果。