Home > Blockchain >  How to make data from a text file be filtered into a vector
How to make data from a text file be filtered into a vector

Time:05-09

I have a little program I don't know how to make. Basically, it is a function to create a vector with data from a text file that meets a parameter in its text.

text_in_vector("file.txt", "10")

text example:

Karen10, Lili12, Stacy13, Mack10

vector results

{"Karen10","Mack10"}

CodePudding user response:

Try something like this:

#include <fstream>
#include <vector>
#include <string>
#include <iomanip>

std::vector<std::string> text_in_vector(const std::string &fileName, const std::string &searchStr)
{
    std::vector<std::string> vec;
    std::ifstream inFile(fileName);
    std::string str;
    while (std::getline(inFile >> std::ws, str, ','))
    {
        if (str.find(searchStr) != std::string::npos)
            vec.push_back(str);
    }
    return vec;
}

Online Demo

  •  Tags:  
  • c
  • Related