Search code examples
c++filegetlinestringstream

Read elements from a txt file that are separeted by a character


I'am working on a program where there are first names, last names and a numbers on a file and i need to read that information into my program. My actual problem is that there is people who doesnt have a second name or second last name. To solve the issue I started trying to read from a file until a specific character is found, For example:

Robert, Ford Black,208   //Where Robert is the first name, and Ford Black are his two last names
George Richard, Bradford,508 //Where George Richard are both his first names, and Bradford is his only last 
                      name

I am saving this information in three separeted string, one that will store first and second name, first last and second last name and the third one for the numbers.

I'm trying to only use native libraries from c++. I've been reading that getline(a,b,c) and IStringStream can actually solve my problem but I don't know how to correctly implement it


Solution

  • It's just a matter of using std::getline with a delimiter character to read out of the string stream. See a simplified example (no error checking) below:

    for (std::string line; std::getline(std::cin, line); )
    {
        std::string firstName, lastName;
        std::istringstream iss(line);
        std::getline(iss, firstName, ',');  // A comma delimits end-of-input
        iss >> std::ws;                     // Skip over any whitespace characters
        std::getline(iss, lastName);        // Read remaining line
        std::cout << "First Name: " << firstName << std::endl;
        std::cout << "Last Name: " << lastName << std::endl;
    }
    

    Note the line iss >> std::ws; using std::ws from <iomanip> is there to eat up extra whitespace characters (which appear after your comma, in your example).

    I'm assuming the C++ line comments in the input are only an annotation for this question, and not part of the actual input.