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

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

概述我刚刚开始重新学习C,因为我在业余时间在高中学习(使用C Primer,第5版).当我进行基本练习时,我注意到以下程序无法在 Xcode中正确执行,但会在Ideone上正确执行: http://ideone.com/6BEqPN #include <iostream>int main() { // currVal is the number we're counting; we'll 我刚刚开始重新学习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;}
总结

以上是内存溢出为你收集整理的c – 程序在Ideone上正确执行,但在Xcode中没有全部内容,希望文章能够帮你解决c – 程序在Ideone上正确执行,但在Xcode中没有所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1005832.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存