【问题标题】:Read strings from the standard input, concatenating what is read into one large string从标准输入读取字符串,将读取的内容连接成一个大字符串
【发布时间】:2018-04-10 10:46:54
【问题描述】:

由于某种原因,我无法让 for 循环工作。 它不打印任何东西。这是代码:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string concatenated;
    for (string buffer; cin >> buffer; concatenated += buffer);
    cout << "The concatenated string is " << concatenated << endl;

    return 0;
}

【问题讨论】:

  • 我无法复制。你真的输入了什么然后按回车吗?
  • @ArkadyGodlin 在这种情况下它应该在那里。
  • @Sniper2Wolf 它工作正常。 See here working
  • 但也许在for(...) 之后有一个空块{} 来电报发生了什么会更好?
  • 我认为你应该添加一个退出字符串代码,以打破 for 循环。在 Visual Studio 2015 上,除了 CTRL+C 我无法退出此循环,并且此键引发异常。

标签: c++


【解决方案1】:

问题是for-loop 不会自动退出。它不断循环并等待下一个输入。这就是为什么你没有得到任何输出。

您应该在 Windows 上输入 Control+Z,在 Unix 平台上输入 Control+D 以在 . 请参阅this 了解更多信息。

代码很好。 See it working here

以下是我本地的输出。使用的代码与发布和可用的代码相同here

【讨论】:

    【解决方案2】:

    你需要一些东西来阻止循环等待更多的输入。你可以使用一个特殊的字符串来做到这一点。

    #include <iostream>
    #include <string>
    
    using std::string;
    using std::cin;
    using std::cout;
    using std::endl;
    
    int main()
    {
        string concatenated;
        for (string buffer; cin >> buffer && buffer!="STOP"; concatenated += buffer);
        cout << "The concatenated string is " << concatenated << endl;
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 2011-02-25
      相关资源
      最近更新 更多