I have a std::string
with multiple lines and I need to read it line by line. Please show me how to do it with a small example.
Ex: I have a string string h;
h will be:
Hello there. How are you today? I am fine, thank you.
I need to extract Hello there.
, How are you today?
, and I am fine, thank you.
somehow.
The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be.
C# StringReader ReadLineThe ReadLine method reads a line of characters from the current string and returns the data as a string. In the example, we count the lines of a multiline string. The ReadLine method returns the next line from the current string, or null if the end of the string is reached.
Show activity on this post. scanf("%[^\n]s",s); this will do you can also use scanf("%[^\n]%*c", s); where s is defined as char s[MAX_LEN] where MAX_LEN is the maximum size of s . Here, [] is the scanset character. ^\n stands for taking input until a newline isn't encountered.
The correct option is (b). Explanation: The function gets() is used for collecting a string of characters terminated by new line from the standard input stream stdin. Therefore gets() is more appropriate for reading a multi-word string.
#include <sstream> #include <iostream> int main() { std::istringstream f("line1\nline2\nline3"); std::string line; while (std::getline(f, line)) { std::cout << line << std::endl; } }
There are several ways to do that.
You can use std::string::find
in a loop for '\n'
characters and substr() between the positions.
You can use std::istringstream
and std::getline( istr, line )
(Probably the easiest)
You can use boost::tokenize
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With