Reputation: 19
In my file every row like this:
"ID: HH-123AB, brand: Mercedes-Benz, 128000 miles, 12 L\n"
ID:, brand: miles, and L is the same in every row. Who can I scan only the HH-123AB, Mercedes-Benz, 128000 and 12?
Upvotes: 0
Views: 1343
Reputation: 1789
You can use the following function to "tokenize" the string
vector<std::string> tokens(const std::string& csv, char separatedBy) {
vector<std::string> tokenized;
stringstream str(csv);
while(!(str.fail())) {
std::string token;
getline(str, token, separatedBy);
tokenized.push_back(token);
}
// Used std::move for performance only, you
// could just return it, but it will be
// copied
return std::move(tokenized);
}
This function "tokenizes" a string by splitting it, using a separator character.
Then, on your main function:
std::string line;
// Get the whole line
getline(cin, line);
// Get all "comma separated tokens"
vector<std::string> commaSeparated = tokens(line, ',');
Then parse every portion of it as you want, for example:
// First space separated token in the first comma separated one
cout << tokens(commaSeparated[0], ' ')[1] << "\n";
// Second space separated token in the second comma separated one
// Note: The first space is considered one
cout << tokens(commaSeparated[1], ' ')[2] << "\n";
// First space separated token in the third comma separated one
cout << tokens(commaSeparated[2], ' ')[1] << "\n";
// First space separated token in the fourth comma separated one
cout << tokens(commaSeparated[3], ' ')[1] << "\n";
Upvotes: 2