C++ Xcode 不会运行我的 for 循环(非常短)

标签 c++ xcode

<分区>

我想继续阅读 Stroustrup PPUC++,但我被卡住了!几天前我写了一个 BleepOutTheBadWords 程序,它工作了。前几天试着和弟弟一起写程序,失败了。这本质上是我编写的一个程序,用于找出问题所在。它不会打印出“句子” vector 中的每个单词。

#include <iostream>
#include "std_lib_facilities.h" // Stroustrup header file
using namespace std; 

int main()
{
    cout << "Write a sentence." << endl;

    vector<string> sentence;

    // Put user input into "sentence" vector
    for (string word; cin >> word; )
        sentence.push_back(word);

    // Print each word in "sentence" vector
    for (int i = 0; i < sentence.size(); ++i)
        cout << sentence[i] << endl;

    // Keep window open and return 0 to show program succeeded    
    keep_window_open();
    return 0;
}

答案很明显。如果您很友善,请只说出显而易见的事情。在发布这篇文章之前,我浏览了两个不同页面上的建议阅读 Material 。

最佳答案

XCode won't run my for loop

您的循环正在运行。您错过的是如何终止循环。

for (string word; cin >> word; )

cin >> word 的计算结果为 false 时,此循环将终止。通常,即没有错误条件,当您输入完成时,它将评估为 false。发出流结束信号或 EOF 的确切过程取决于平台。如果您在 OSX 上运行此程序,那么发出 EOF 信号的最常见方式是按 Ctrl + D 按钮,除非您更改了键盘的默认配置。一旦您发出 EOF 信号,此输入循环将终止,您将能够看到输出。

我非常确定 Stroustrup 在他的书中讨论了这一点(尽管我无法提供确切的页码)。然而,他的书中的“第 10 章:输入和输出流”详细介绍了这些内容。

关于C++ Xcode 不会运行我的 for 循环(非常短),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46441652/

相关文章:

c++ - 将 std::string 转换为 Swift 字符串

c++ - int&a 和 int &a 有区别吗?

xcode - SKSpriteNode 通过触摸拖动移动

ios - 快速添加多个 slider 的值然后取平均值?

swift - 为什么 iOS 13.2 中的 MPPlayableContentManager 协议(protocol)(MPPlayableContentDataSource 和 MPPlayableContentDelegate)没有被调用?

c++ - 将一些代码从 C++ 转换为 C

C++ 范围问题 : Creating a matrix class without wasting space

c++ - 使用链接列表复制 Ctor

xcode - 使用 InstantiateViewController 传递数据

ios - WatchOS 2 : "Cannot Install Watch App" "Error Launching ' TestApp WatchKit App Extension'"