I’ve spent almost 4 hours trying to get past this issue…
I have a text file with over 100 rows. Each row has 4 values separated by commas. I want to be able to extract each value and save it into a variable (v1…v4).
I have used a for loop, as I won’t be reading the entire contents of the file. I’m just trying to get 1 working for now.
So far, I have managed to read a single row. I just need to break the row up now. This is for my Uni assignment, and I am not allowed to use any boost or tokeniser classes. Just getline and other basic commands.
I have this code:
// Read contents from books.txt file
ifstream theFile("fileName.txt");
string v1, v2, v3, v4, line;
for (int i = 0; i < 1; i++) {
getline(theFile, line, '\n');
cout << line << endl; // This part works fine
getline(line, v1, ","); // Error here
cout << v1 << endl;
getline(line, v2, ","); // Error here
cout << v2 << endl;
getline(line, v3, ","); // Error here
cout << v3 << endl;
getline(line, v4, '\n'); // Error here
cout << v4 << endl;
}
theFile.close();
The error I get is – error: no matching function for call to ‘getline(std::string&, std::string&, const char [2])
How can I fix this?
The delimiter for getline is a character. You have used double-quote marks
","which represent a string (hence why the compiler error indicates that you’ve usedchar[2]– string literals contain an additional ‘nul’ character).Single character values are represented using single quotes instead:
edit – I’ve just noticed you’re passing a string as the first parameter, which getline doesn’t support (it won’t let you retrieve tokens directly from a string). You probably wanted to stuff the string into a
stringstreaminstead