繁体   English   中英

如何接受c++中未知行数,每行有两个字符串

[英]How to accept an unknown number of lines in c++, each line has two strings

如何接受 c++ 中的未知行数? 每行有两个字符串,中间用空格分隔。 我尝试了This cplusplus forum中提到的解决方案,但没有一个解决方案对我有用。 只有在每行末尾按下Enter时,其中一种解决方案才有效。 我不确定是否会在输入行的末尾给出\n字符。 我有哪些选择?

我目前的尝试要求我按Ctrl+Z结束这些行。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector> 
using namespace std;

int main(){
    string line; 
    while(cin>>line and cin.eof()==false){
        cout<<line<<'\n';
    }
    return 0;
}

我想采用未知数量的字符串,如下所示:

cool toolbox
aaa bb
aabaa babbaab

请不要将此标记为重复项,我真的尝试了所有我能找到的方法,我在上面由 m4ster r0shi (2201) 给出的链接上尝试了以下解决方案。 但它对我不起作用。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<string> words;

    string word;
    string line;

    // get the whole line ...
    getline(cin, line);

    // ... then use it to create
    // a istringstream object ...
    istringstream buffer(line);

    // ... and then use that istringstream
    // object the way you would use cin
    while (buffer >> word) words.push_back(word);

    cout << "\nyour words are:\n\n";

    for (unsigned i = 0; i < words.size(); ++i)
        cout << words[i] << endl;
}

这个其他解决方案也没有用:其他解决方案,我也试过这个 SO 帖子: Answers to similar ques 这个适用于我的示例,但是当我只传递一行输入时,它会冻结。

// doesn't work for single line input 
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector> 
using namespace std;

int main(){
    string line ="-1"; 
    vector<string>data;
    while(1){
        cin>>line;
        if(line.compare("-1")==0) break;
        data.push_back(line);
        line = "-1";
    }
    for(int i =0;i<data.size();i+=2){
        cout<<data[i]<<' '<<data[i+1]<<'\n';
    }
    return 0;
}

如果每一行都有两个由空格分隔的单词,那么也许您应该有一个Line结构,其中包含两个std::string并为std::istream重载>>运算符。

然后你可以从std::cin复制到向量中。

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

struct Line {
    std::string first;
    std::string second;
};

std::istream& operator>>(std::istream& i, Line& line) {
    return i >> line.first >> line.second;
}

int main() {
    std::vector<Line> lines;

    std::copy(
      std::istream_iterator<Line>(std::cin),
      std::istream_iterator<Line>(),
      std::back_inserter(lines)
    );

    for (auto &[f, s] : lines) {
        std::cout << f << ", " << s << std::endl;
    }

    return 0;
}

试运行:

% ./a.out                
jkdgh kfk
dfgk 56
jkdgh, kfk
dfgk, 56

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM