c – 程序在Ideone上正确执行,但在Xcode中没有

我刚刚开始重新学习C,因为我在业余时间在高中学习(使用C Primer,第5版).当我进行基本练习时,我注意到以下程序无法在
Xcode中正确执行,但会在Ideone上正确执行:
http://ideone.com/6BEqPN

#include <iostream>

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

    // read first number and ensure that we have data to process
    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;
}

在XCode中,程序没有完成.它在while循环体的最后一次执行中停止.在调试控制台中,我看到有信号SIGSTOP.
Screenshot

这是我第一次将Xcode用于任何类型的IDE.我怀疑它可能与我的构建设置有关?我已经为GNU 11配置了它并使用libstdc.

我很欣赏任何关于为什么这段代码可以在Ideone上工作但不在Xcode上工作的见解.另外,我想知道哪些IDE是首选的,如果Xcode适合学习C 11.谢谢!

最佳答案 你的cin永远不会停止.你的while循环条件是std :: cin>> val,所以循环将运行,直到输入不是数字的东西.处理完输入线(42 42 42 42 42 55 55 62 100 100 100)后,cin未处于故障状态,只是等待新输入.如果您输入的不是数字,您的循环将正确完成(例如42 42 42 42 42 55 55 62 100 100 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;
}
点赞