如何在 c++ 中将 getline() 拆分为数组
How can I split a getline() into array in c++
我有一个输入获取线: man,meal,moon;fat,food,feel;cat,coat,cook;love,leg,lunch
我想在看到;
时将其拆分为一个数组,它可以将;
之前的所有值存储在数组中。
例如:
array[0]=man,meal,moon
array[1]=fat,food,feel
等等...
我该怎么做?我尝试了很多次,但我失败了! 谁能帮忙?
提前谢谢。
您可以使用
std::stringstream
和std::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
相关文章:
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- 拆分字符数组并存储为向量
- 通过拆分字符数组来创建字符串
- 在C++中用字符串数组拆分声明和赋值
- 如何拆分整数并将所有内容添加到数组中?
- 将字符拆分为字符数组
- C++字符串数组在 20 字节后拆分
- 按空格拆分字符串并将列输出到不同的数组中
- 如何在 c++ 中将字符串拆分为字符串 2d 数组数组
- 使用C 从定界线拆分字符串中提取整数数组
- C++将大型数组拆分/分区为较小的数组
- 拆分数组的更轻松的方法是什么?
- 如何调试此代码以按空格将数组拆分
- 在没有OPENCV的C 中,RGB数组的拆分通道
- 在 C++ 中拆分数组的可能性
- 将一个std::数组拆分为一个较小大小的std::array元组
- 练习:将数组值拆分为正数组和负数组
- c++中拆分数组字符串