3

In c++, how can I iterate through each line in a string? There have been plenty of questions regarding reading a file line by line, but how can I do this with a std::string?

For example, if I have the following string:

1051
2232
5152
3821
0021
3258

How would I iterate through each number?

Christian Stewart
  • 15,217
  • 20
  • 82
  • 139
  • @JerryCoffin I don't think it's the same, I'm not using `cin` and I don't want to read anything into a `std::string`. – Christian Stewart Jul 23 '13 at 18:49
  • @ChristianStewart: Sorry, I mis-read -- didn't understand that the string is your source instead of destination. In this case, `stringstream` is your friend. – Jerry Coffin Jul 23 '13 at 20:31

2 Answers2

2

In c++, you can use string exactly as files, using the classes defined in the sstream header:

#include <sstream>
//...
std::string str=...; // your string
std::istrstream in(str); // an istream, just like ifstream and cin
std::string line;
while(std::getline(in,line)){
  //do stuff with line
}

This is a bit simplistic, but you get the idea.

You can use in just as you would use cin, e.g. in>>x etc. Hence the solutions from How do I iterate over cin line by line in C++? are relevant here too - you might want to look at them for the "real" answer (just replace cin with your own istream

Edit: As a side note, you can create strings in the same way you print to the screen, using the ostream mechanism (like cout):

std::ostringstream out;
out << header << "_" << 3.5<<".txt";
std::string filename=out.str();
Community
  • 1
  • 1
rabensky
  • 2,864
  • 13
  • 18
0

Use a tokenizer and let '\n' or '\r\n' or the appropriate newline for your OS be the token splitter..

Or if you were using a buffered file stream reader, just create a stringstream from this new string and read from the string stream instead of the file stream.

In short nothing changes except that you aren't reading from a file.

A horribly naive solution would be to make a string stream from this and assign ints or strings in a while loop from it.

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46