按行和空格分开字符串(使用getline)

时间:2015-04-04 01:07:11

标签: c++ vector delimiter getline

我试图读取标准输入行并将每个字符串放在一行(用空格分隔)到矢量字符串向量的索引中,然后将每一行放在一个单独的索引中,但我&#39 ;我混淆了如何使用getline来做这件事。

例如,说我的标准是:

Hello
I want a
sand wich

字符串向量的向量看起来像:

0: {"Hello"}
1: {"I", "want", "a"}
2: {"sand", "wich"}

我试图编写类似这样的代码:

vector <vector <string> > name;
string line, s;
int count= -1;
while(getline(cin, line, '\n'))
{
    count++;
    while (getline(line, s, ' '))
    {
        name[count].push_back(s);
    }
}

这会做我想做的事吗?

哦,所以用字符串流,像这样?

vector <vector <string> > name;
string line, string;
stringstream ss;
int count= -1;
while(getline(cin, line, '\n'))
{
    count++;
    ss.str(line);
    while (ss >> string)
    {
        name[count].push_back(string);
    }
    ss.clear();
}

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码。

vector <vector <string> > name;
vector<string> tmp;
string line, str;//It should not be string
stringstream ss;
int count= -1;//no need for count variable as pushing to a vector starts from 0
while(getline(cin, line, '\n'))
{
    count++;
    ss.str(line);
    while(ss >> str)
    {
        tmp.push_back(str);//extracting tokens of string in tmp vector
    }
    name.push_back(tmp);//pushing vector of string to main vector
    tmp.clear();
    ss.clear();
}