读取由空格分隔的字符串到C++向量中

Reading string separated by spaces into vector in C++

本文关键字:C++ 向量 字符串 空格 分隔 读取      更新时间:2023-10-16

这是我的测试.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 的评论,您的代码现在不起作用。