Stream Out Part of a string

107 views Asked by At

I want to stream out a std::string but I want to be able to do it without the first two characters or the last two characters.

For example:

string foo{"bu blah blah blee le"};

cout << foo.substr(2) << endl << foo.substr(0, foo.size() - 2) << endl;

Are there any iomanip tools for that? or should I just go ahead and construct the temporary strings?

1

There are 1 answers

1
Barry On BEST ANSWER

You could use cout.write:

cout.write(foo.c_str() + 2, foo.size() - 4);

which also returns the stream, so you can do:

cout << "First two: ";
cout.write(foo.c_str(), 2) << "\nAll but first two: ";
cout.write(foo.c_str() + 2, foo.size() - 2) << '\n';