【问题标题】:how to extract two strings from a line c++如何从一行c ++中提取两个字符串
【发布时间】:2017-07-18 11:24:34
【问题描述】:

假设我必须阅读以下输入:

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay
str1 str2

atcay
ittenkay
oopslay

所以我无法单独存储所有字符串。 这是我能想到的部分代码。

while(1)
{
    getline(cin,s);
    if(s.empty())
        break;
    else
        cout<<s<<endl;
}

所以现在我可以将“dog ogday”存储在一个字符串中。但我想将它们存储在单独的字符串中。请帮忙。(在此先感谢:D)

【问题讨论】:

  • 你听说过&gt;&gt;吗?您通常会在到达getline 之前了解它。

标签: c++ string input cin getline


【解决方案1】:

使用cin 获取两个字符串:

  string a,b;
  cin >> a >> b;

【讨论】:

    【解决方案2】:
    int i=0;
    while(i<9){
       getline(cin,s);
       if(s.empty())
         break;
       else
        cout<<s<<endl;
       i++;
      }
    

    不确定这是否是您想要的,但我认为它可以让您存储所有 9 个字符串。

    【讨论】:

    • 幻数 9...另外,您应该先测试您的代码。
    【解决方案3】:

    这会分别读取所有“单词”(以空格分隔)。

    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main()
    {
        for (std::string s; std::getline(std::cin, s) && !(s.empty() || s.find_first_not_of(' ') == std::string::npos); )
        {
            std::istringstream stream{s};
            for (std::string str; stream >> str; std::cout << str << '\n');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 2014-05-26
      相关资源
      最近更新 更多