程序在Ideone上正确执行,但不能在Xcode中执行 我刚刚开始重新学习C++,因为我在课余时间用高中学习它(使用C++入门,第五版)。在进行基本练习时,我注意到以下程序在Xcode中无法正确执行,但在Ideone上可以正确执行: #包括 int main(){ //currVal是我们正在计算的数字;我们将把新值读入val int currVal=0,val=0; //读取第一个数字并确保我们有数据要处理 如果(标准::cin>>当前值){ int-cnt=1; while(std::cin>>val){ 如果(val==currVal) ++碳纳米管; 否则{ std::cout

程序在Ideone上正确执行,但不能在Xcode中执行 我刚刚开始重新学习C++,因为我在课余时间用高中学习它(使用C++入门,第五版)。在进行基本练习时,我注意到以下程序在Xcode中无法正确执行,但在Ideone上可以正确执行: #包括 int main(){ //currVal是我们正在计算的数字;我们将把新值读入val int currVal=0,val=0; //读取第一个数字并确保我们有数据要处理 如果(标准::cin>>当前值){ int-cnt=1; while(std::cin>>val){ 如果(val==currVal) ++碳纳米管; 否则{ std::cout,c++,xcode,c++11,C++,Xcode,C++11,你的cin从不停止。你的while循环的条件是std::cin>>val,因此循环将一直运行,直到输入了非数字的内容。在输入行之后(42 42 55 62 100)处理后,cin没有处于失败状态,它只是等待新的输入。如果输入的内容不是数字,则循环将正确完成(例如42 42 55 62 100 x) 如果要读取单行输入,应使用std::getline和stringstream: #include <iostream> #include <sstream> int main

你的
cin
从不停止。你的
while
循环的条件是
std::cin>>val
,因此循环将一直运行,直到输入了非数字的内容。在输入行之后(
42 42 55 62 100
)处理后,
cin
没有处于失败状态,它只是等待新的输入。如果输入的内容不是数字,则循环将正确完成(例如
42 42 55 62 100 x

如果要读取单行输入,应使用
std::getline
stringstream

#include <iostream>
#include <sstream>

int main() {
    // currVal is the number we're counting; we'll read new values into val
    int currVal = 0, val = 0;

    string str;
    //read the string
    std::getline(std::cin, str);
    //load it to the stream
    std::stringstream ss(str);

    //now we're working with the stream that contains user input
    if (ss >> currVal) {
        int cnt = 1;
        while (ss >> 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;
}
#包括
#包括
int main(){
//currVal是我们正在计算的数字;我们将把新值读入val
int currVal=0,val=0;
字符串str;
//读字符串
std::getline(std::cin,str);
//将其加载到流中
std::stringstream ss(str);
//现在我们正在处理包含用户输入的流
如果(ss>>当前值){
int-cnt=1;
while(ss>>val){
如果(val==currVal)
++碳纳米管;
否则{

std::cout另一种停止的方法是关闭输入,当使用as
echo 42 42 42 42 42 55 55 62 100 | my_prog
@singerofall时会发生这种情况。如果条件是..
(std::cin>>val&&val)
您的问题是交互输入与输入“关闭”的关系。
#include <iostream>
#include <sstream>

int main() {
    // currVal is the number we're counting; we'll read new values into val
    int currVal = 0, val = 0;

    string str;
    //read the string
    std::getline(std::cin, str);
    //load it to the stream
    std::stringstream ss(str);

    //now we're working with the stream that contains user input
    if (ss >> currVal) {
        int cnt = 1;
        while (ss >> 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;
}