C++ 将由空格分隔的字符串读入C++;

C++ 将由空格分隔的字符串读入C++;,c++,string,file,vector,text-files,C++,String,File,Vector,Text Files,下面是my test.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 我想将test.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 "

下面是my test.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
我想将test.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;
}
#包括“test.txt”
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
结构M
{
int x;
int-y;
intz;
};
int main(){
ifstream文件;
打开(“test.txt”);
字符串值;
M-XYZ;
向量向量机;
如果(文件){
while(getline(文件、值)){
XYZ.x=stoi(值);
如果(值==“”)
XYZ.y=stoi(值);
如果(值==“”)
XYZ.z=stoi(值);
}
向量推回(XYZ);
}
其他的

cout使用
std::stringstream
应该可以减少出错的可能性

while (getline(file, value))
{
      std::stringstream ss(value); // must #include <sstream>
      ss >> XYZ.x >> XYZ.y >> XYZ.z;
}
while(getline(文件,值))
{
std::stringstream ss(value);//必须#包括
ss>>XYZ.x>>XYZ.y>>XYZ.z;
}

由于@Jonathan Potter的评论,您的代码现在无法运行。

…那么问题出在哪里?您的问题是什么?您好,欢迎来到StackOverflow!请告诉我们您的代码有什么问题。如果这是代码改进问题,那么最好在询问时询问,我会用
std::stringstream ss;
,请参阅,然后使用
ss
填充结构,如
ss>>XYZ.x>>XYZ.y>>XYZ.z;
这样,您就不必关心空格等。我认为问题在于代码不起作用。首先,为什么要包含“text.txt”?第二次,您将输入读取到Vec向量中,但正在打印移动向量?代码是否完整?您在同一字符串上调用了三次
stoi(value)
。调用
stoi
不会修改输入字符串。谢谢。但是,当我尝试打印内容时,出现错误:无法绑定'std::ostream'{aka std::basic_ostream}将左值改为std::basic_ostream&&'cout这是因为
Moves[i]
是一个
struct
。尝试分别显示每个元素,如
cout