Search code examples
c++splitifstream

Ifstream, how to read next line after facing a specific character


    (example.txt)
    Tommy:16:Male
    Sam:23:Female

I wanted to code in C++ that take a data from the text file using ifstream but not the entire line. For example, the first column represent Name and I just want to take Name data.

Is there a way to split ":" this character, just like Java line.split(":").


Solution

  • std::ifstream infile("example.txt");
    
    std::string line;
    while (std::getline(infile, line))
    {
        std::stringstream ss;
        ss.str(line);
        std::string item;
        while (getline(ss, item, ':')) {
            std::cout << item << std::endl;
        }
    }