c++ - 将逗号分隔的数据分配给 vector

标签 c++ file vector delimiter

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

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

等我知道大小,我希望每条线在 vector 中都是它自己的对象。

这是我的实现:

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 << fileLine

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

这里有人可以提供任何帮助吗?

最佳答案

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

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

关于c++ - 将逗号分隔的数据分配给 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16628130/

相关文章:

c++ - 何时使用 "identity"tmp 技巧?

c++ - 多生产者单消费者队列

java - 改进从 Java 中的文本文件中提取数据

c++ - 为 vector 成员提供默认值并更新元素

c++ - 如何释放 unordered_map 内存?

c++ - 链接到静态库时出现 undefined reference 错误

c - 变量文件可能尚未初始化

c - C中的读/写函数

c++ - 按位与不计算期望值

c++ - 为什么 vector.size() 函数会给我一个错误?