Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ process string one by line

So I have string:

string message = "Hello\nHow are you?\nGood!"

I want to get it line by line in this format:

string line = "";

for (getline(message, line)) {
    // do something with the line
}

How can I achieve this? It doesn’t matter if getline will be in use.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to split the string by \n but I can’t go through it with for loop

>Solution :

getline requires an input stream to work on. Fortunately, we have std::stringstream which you can probably tell from the name is a stream of a string. Using that changes your code to

std::string line;
std::stringstream ss(message);
while(getline(ss, line)) {
    // do something with the line
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading