简体   繁体   English

将逗号分隔的数据分配给vector

[英]Assigning Comma Delimited Data to Vector

I have some comma delimited data in a file, like so: 我在文件中有一些用逗号分隔的数据,如下所示:

116,88,0,44 66,45,11,33 116,88,0,44 66,45,11,33

etc. I know the size, and I want each line to be its own object in the vector. 等。我知道大小,并且我希望每一行都是向量中自己的对象。

Here is my implementation: 这是我的实现:

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;

} }

No luck so far. 到目前为止没有运气。 I get errors in the 我在

stream1 << fileLine stream1 << fileLine

and the push_back statement. 和push_back语句。 The stream1 one tells me there's no match for the << operator (there should be; I included the library) and the latter tells me movingObjects is undeclared, seemingly thinking that it is a function, when it is defined in the header as my vector. stream1告诉我<<操作符不匹配(应该存在;我包含了库),而后者告诉我moveObjects未声明,似乎是在标题中将其定义为我的向量时认为它是一个函数。 。

Can anyone offer any assistance here? 有人可以在这里提供任何帮助吗? Much appreciated! 非常感激!

If I understood correctly your intentions this should be close to what you're trying to do: 如果我正确理解了您的意图,这应该与您要执行的操作接近:

#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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM