Whatamia Whatamia - 1 month ago 12
C++ Question

Using getline to divide input, using commas as delim

I have a text file with movie info, separated by commas. I will provide a line for insight:

8,The Good the Bad and the Ugly,1966,2


I need to take this line, and divide the different pieces by their comma to fit the format of this function:

void addMovieNode(int ranking, std::string title, int releaseYear, int quantity);


The text file's information is in order with the function but I am unclear on how the getline operation operates.

I know I can pass in the text file like

getline("moveInfo.txt", string, ",");


but how will that translate in terms of what is actually going on with the output?

I read the manual on the cplusplus website but that did not help to clarify very much.

Answer

You can use a string and stringstream:

#include <sstream>
#include <string>
#include <fstream>

ifstream infile( "moveInfo.txt" );    
while (infile)
{
    std::string line;
    if (!std::getline( infile, line,',' )) break;
    std::istringstream iss(line);
    int ranking, releaseYear, quantity;
    std::string title;
    if (!(iss >> ranking >> title >> releaseYear >> quantity)) { break; } 
}
Comments