1

我在文件中有一些逗号分隔的数据,如下所示:

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;

}

到目前为止没有运气。我在

流 1 << 文件行

和 push_back 语句。stream1 告诉我 << 运算符不匹配(应该有;我包含了库),后者告诉我movingObjects 未声明,似乎认为它是一个函数,当它在标题中定义为我的向量时.

任何人都可以在这里提供任何帮助吗?非常感激!

4

1 回答 1

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;
    }
}
于 2013-05-18T22:39:47.200 回答