【问题标题】:Assigning Comma Delimited Data to Vector将逗号分隔的数据分配给向量
【发布时间】: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&lt;int&gt; movingObjects(); 是一个函数声明,如果那是你写的。要调用默认构造函数,std::vector&lt;int&gt; movingObjects{}; 可以,std::vector&lt;int&gt; movingObjects; 也可以。不需要任何形式的括号/大括号。
  • 在 StackOverflow 中搜索“矢量文件”。到目前为止,这些相关问题太多了。
  • 另外,将getline 放入循环条件中,这样它就不会使用失败的读取。
  • 我进行了搜索,不幸的是我没有找到任何对我的具体案例有帮助的东西。逗号分隔的数据相当棘手。根据我的数据文件示例,我应该澄清矢量对象有一些属性,但它们都是整数。修复了一些小问题,仍然有问题。

标签: c++ file vector delimiter comma


【解决方案1】:

如果我正确理解你的意图,这应该接近你想要做的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2018-04-13
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    相关资源
    最近更新 更多