Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a string line by line using c++

Tags:

c++

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.

like image 550
raagavan Avatar asked Feb 20 '11 18:02

raagavan


People also ask

How do you read each line in a file C?

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.

How read a string from line by line in C#?

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.

How do you read a sentence in C?

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.

What is the most preferred function to read a string in C?

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.


2 Answers

#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;     } } 
like image 79
Martin Stone Avatar answered Sep 29 '22 15:09

Martin Stone


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

like image 23
CashCow Avatar answered Sep 29 '22 15:09

CashCow