0

I have this code:

string text;
getline(cin ,text);
istringstream iss(text);
copy(
    istream_iterator<string>(iss),
    istream_iterator<string>(),
    ostream_iterator<string>(cout,"\n")
);

When I input a string like: bf "inging" filename, it outputs:

bf
"inging"
filename

Is there a way such that I can take each individual output and save it into a variable?

user2757849
  • 227
  • 3
  • 4
  • 14

1 Answers1

0

It is certainly possible to capture the different output and do something with them: you'd create a stream buffer which detects newlines and does something with the characters received since the last newline. Only then you'd forward the string somewhere else. Although doable, I doubt this is really what you want to do.

If you want to capture all std::strings from a stream and you don't want each one to have a specific name, e.g., because you don't know how many strings to expect, you could store them into std::vector<std::string> using

std::vector<std::string> strings{ std::istream_iterator<std::string>(iss),
                                  std::istream_iterator<std::string>() };

... or

std::vector<std::string> strings;
std::copy(std::istream_iterator<std::string>(iss),
          std::istream_iterator<std::string>(),
          std::back_inserter(strings));

If you want to have the strings in individual variables you'd just read them into the variables and make sure you read all variables:

std::string a, b, c;
if (iss >> a >> b >> c) {
    std::cout << "read a='" << a << "' b='" << b << " c='" << c << "'\n";
}
else {
    std::cout << "failed to read three strings from line '" << text << "'\n";
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380