读取由空格分隔的字符串到C++向量中
Reading string separated by spaces into vector in C++
这是我的测试.txt的样子:
18 19 20
21 22 23
22 23 24
23 24 25
24 25 26
25 26 27
28 29 30
29 30 31
我想在测试中读取整数.txt作为字符串,然后创建一个 3 个整数的向量。如果这是有意义的,那么输出是一个向量,如下所示:
18 19 20, 21 22 23, 22 23 24, 23 24 25, 24 25 26, 25 26 27, 28 29 30, 29 30 31
这是我的代码:
#include "test.txt"
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <vector>
using namespace std;
struct M
{
int x;
int y;
int z;
};
int main(){
ifstream file;
file.open("test.txt");
string value;
M XYZ;
vector<M> Vec;
if (file){
while (getline(file, value)){
XYZ.x = stoi(value);
if (value == " ")
XYZ.y = stoi(value);
if (value == " ")
XYZ.z = stoi(value);
}
Vec.push_back(XYZ);
}
else
cout << "Error openning file." << endl;
for (int i = 0; i < Vec.size(); i++)
cout << Vec[i] << endl;
return 0;
}
我想我正确地使用了 getline 和 stoi,但可能是错误的。在大多数情况下,逻辑似乎是正确的。提前谢谢。
使用std::stringstream
应该使事情变得不那么容易出错
while (getline(file, value))
{
std::stringstream ss(value); // must #include <sstream>
ss >> XYZ.x >> XYZ.y >> XYZ.z;
}
由于@Jonathan Potter 的评论,您的代码现在不起作用。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么