C++如何从字符串中读取两行来分隔字符串?

0 c++ string

我有两行字符串foo:

string foo = "abc \n def";
Run Code Online (Sandbox Code Playgroud)

我如何从字符串foo读取这两行:第一行到字符串a1和第二行到字符串a2?我需要完成:string a1 ="abc"; string a2 ="def";

Mar*_*ork 8

使用字符串流:

#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::string       foo = "abc \n def";
    std::stringstream foostream(foo);

    std::string line1;
    std::getline(foostream,line1);

    std::string line2;
    std::getline(foostream,line2);

    std::cout << "L1: " << line1 << "\n"
              << "L2: " << line2 << "\n";
}
Run Code Online (Sandbox Code Playgroud)

检查此链接以了解如何读取行,然后将行拆分为单词:
C++打印限制单词数