如何在 c++ 中将 getline() 拆分为数组

How can I split a getline() into array in c++

本文关键字:拆分 数组 getline c++ 中将      更新时间:2023-10-16

我有一个输入获取线: man,meal,moon;fat,food,feel;cat,coat,cook;love,leg,lunch

我想在看到;时将其拆分为一个数组,它可以将;之前的所有值存储在数组中。

例如:

array[0]=man,meal,moon

array[1]=fat,food,feel

等等...

我该怎么做?我尝试了很多次,但我失败了! 谁能帮忙?

提前谢谢。

您可以使用

std::stringstreamstd::getline

我还建议您使用std::vector,因为它可以调整大小。

在下面的示例中,我们获取输入行并将其存储到std::string中,然后我们创建一个std::stringstream来保存该数据。您可以使用带有;std::getline作为分隔符将分号之间的字符串数据存储到变量word中,如下所示,每个"单词"被推回向量:

int main()
{
    string line;
    string word;
    getline(cin, line);
    stringstream ss(line);
    vector<string> vec;
    while (getline(ss, word, ';')) {
        vec.emplace_back(word);
    }
    for (auto i : vec) // Use regular for loop if you can't use c++11/14
        cout << i << 'n';

或者,如果您无法使用std::vector

string arr[256];
int count = 0;
while (getline(ss, word, ';') && count < 256) {
    arr[count++] = word;
}

现场演示

输出:

man,meal,moon
fat,food,feel
cat,coat,cook
love,leg,lunch