【问题标题】:Splitting strings separately by line and by blank space (using getline)按行和空格分别拆分字符串(使用 getline)
【发布时间】:2015-06-09 02:29:10
【问题描述】:

我正在尝试读取标准输入的行并将每个字符串放在一行(由空格分隔)到向量字符串向量的索引中,然后将每一行放在单独的索引中,但我很困惑我如何使用 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) 你可以试试运行看看。 2)如果它没有编译,请考虑 vector[count].push_back更新后:为什么需要vector&lt; vector&lt; string &gt; &gt;
  • 您需要为第二个 getline 使用字符串流。
  • 因为我正在编写的程序需要将信息存储在字符串向量的向量中。是为了上课。而且我认为您可以使用 getline 将 cin 转换为字符串?我想我的老师以前做过。

标签: c++ vector delimiter getline


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2018-12-13
    • 2011-02-07
    • 1970-01-01
    相关资源
    最近更新 更多