Read a string line by line using c++

前端 未结 5 1613
不思量自难忘°
不思量自难忘° 2020-12-15 03:30

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

5条回答
  •  自闭症患者
    2020-12-15 04:27

    If you'd rather not use streams:

    int main() {
      string out = "line1\nline2\nline3";
      size_t start = 0;
      size_t end;
      while (1) {
        string this_line;
        if ((end = out.find("\n", start)) == string::npos) {
          if (!(this_line = out.substr(start)).empty()) {
            printf("%s\n", this_line.c_str());
          }
    
          break;
        }
    
        this_line = out.substr(start, end - start);
        printf("%s\n", this_line.c_str());
        start = end + 1;
      }
    }
    

提交回复
热议问题