【发布时间】:2013-05-18 19:24:29
【问题描述】:
我在一个文件中有一些逗号分隔的数据,如下所示:
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
和 push_back 语句。 stream1 告诉我
有人可以在这里提供任何帮助吗?非常感谢!
【问题讨论】:
-
std::vector<int> movingObjects();是一个函数声明,如果那是你写的。要调用默认构造函数,std::vector<int> movingObjects{};可以,std::vector<int> movingObjects;也可以。不需要任何形式的括号/大括号。 -
在 StackOverflow 中搜索“矢量文件”。到目前为止,这些相关问题太多了。
-
另外,将
getline放入循环条件中,这样它就不会使用失败的读取。 -
我进行了搜索,不幸的是我没有找到任何对我的具体案例有帮助的东西。逗号分隔的数据相当棘手。根据我的数据文件示例,我应该澄清矢量对象有一些属性,但它们都是整数。修复了一些小问题,仍然有问题。
标签: c++ file vector delimiter comma