Splitting a string into multiple strings line by line

I'm new to C++ but competent in VB, and I've just come to play about with strings in C++.

I'm writing a function that manipulates a string variable (using the string library) and returns it as a string. The input string can contain "\n" to denote new lines (but sometimes my infact be just one line with no \n's), but my function needs to handle each line individually before joining the string back together and returning it. How do I go about splitting the string line by line so I can manipulate each line?
To split a string into multiple strings, use a stream. Specifically use a stringstream:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stringstream>

int main()
{
    std::string MasterString = "Super cali\nfragelistic \n expialadogis\n then more words\n hello world";
    std::stringstream iss(MasterString);
    
    while(iss.good())
    {
        std::string SingleLine;
        getline(iss,SingleLine,'\n');
        // Process SingleLine here
    }
}
Thanks for that! :) That's useful to know, much easier way to do it!

However, I was doing this as more of an exercise in learning to use functions within "string" and string manipulation more than anything else, just so I can get the hang of it.

I've managed to write a small loop the counts the occurrences of \n and so I have my number of lines stored in an int variable (numlines). Now I want to declare a string array for the lines, but when I use;

string line[numlines];

...to define the array, I get an error that the size expression must be a constant. How can I get around that?

Topic archived. No new replies allowed.