我在文件中有一些逗号分隔的数据,如下所示:
116,88,0,44 66,45,11,33
等。我知道大小,我希望每一行都是它在矢量中的对象。
这是我的实施:
bool addObjects(string fileName) {
ifstream inputFile;
inputFile.open(fileName.c_str());
string fileLine;
stringstream stream1;
int element = 0;
if (!inputFile.is_open()) {
return false;
}
while(inputFile) {
getline(inputFile, fileLine); //Get the line from the file
MovingObj(fileLine); //Use an external class to parse the data by comma
stream1 << fileLine; //Assign the string to a stringstream
stream1 >> element; //Turn the string into an object for the vector
movingObjects.push_back(element); //Add the object to the vector
}
inputFile.close();
return true;
}
到目前为止没有运气。我在
中遇到错误stream1&lt;&lt; fileLine
和push_back语句。 stream1告诉我&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;运算符(应该有;我包括库),后者告诉我movingObjects是未声明的,似乎认为它是一个函数,当它在标题中定义为我的向量时。
有人可以在这里提供任何帮助吗?非常感谢!
答案 0 :(得分:0)
如果我理解你的意图,这应该接近你想要做的事情:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
void MovingObj(std::string & fileLine) {
replace(fileLine.begin(), fileLine.end(), ',', ' ');
}
bool addObjects(std::string fileName, std::vector<int> & movingObjects) {
std::ifstream inputFile;
inputFile.open(fileName);
std::string fileLine;
int element = 0;
if (!inputFile.is_open()) {
return false;
}
while (getline(inputFile, fileLine)) {
MovingObj(fileLine); //Use an external class to parse the data by comma
std::stringstream stream1(fileLine); //Assign the string to a stringstream
while ( stream1 >> element ) {
movingObjects.push_back(element); //Add the object to the vector
}
}
inputFile.close();
return true;
}
int main() {
std::vector<int> movingObjects;
std::string fileName = "data.txt";
addObjects(fileName, movingObjects);
for ( int i : movingObjects ) {
std::cout << i << std::endl;
}
}