使用c ++逐行读取字符串

raa*_*van 35 c++

std::string有多行,我需要逐行阅读.请用一个小例子告诉我如何做到这一点.

例如:我有一个字符串 string h;

h将是:

Hello there.
How are you today?
I am fine, thank you.
Run Code Online (Sandbox Code Playgroud)

我需要提取Hello there.,How are you today?I am fine, thank you.莫名其妙.

Mar*_*one 64

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Cas*_*Cow 11

有几种方法可以做到这一点.

您可以std::string::find在循环中使用'\n'位置之间的字符和substr().

你可以使用std::istringstreamstd::getline( istr, line )(可能是最简单的)

您可以使用 boost::tokenize