Austin
Austin

Reputation: 7339

How to format vector<string> and push_back() into other vectors?

Basically the sudo-code I'm trying to figure out how to do is like this:

vector<string> lines; // filled by txt file where each line is formatted: "string int"
vector<string> queries;
vector<int> counts;

for (int i = 0; i < lines.size(); i++){
    format(lines[i], "%s %d", queries.push_back(%s), queries.push_back(%d));
}

I have no clue what function achieves this. I tried scanf() and strtok(), but ran into problems with both. Is there a better way?

Upvotes: 0

Views: 249

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

scanf() and strtok() is C, not C++.

In C++, you use std::istringstream, and operator>>, for example:

#include <sstream>

std::string line="apple 42";

std::istringstream i(line);

std::string fruit;
int count;

i >> fruit >> count;

if (i.fail())
{
     // Parsing error, up to you what to do about it.
}

Once you have you string, and integer parsed, then you push it into your vectors, as usual.

Upvotes: 1

Related Questions