ostringstream ss;
ss << "(1,2)\n" << "(1,3)\n" << "(1,4)\n" ;
cout << ss.str();

应该打印以下内容:



我如何按行反转输出,以便打印:

最佳答案

将原始代码与C++ 98 一起使用:

  ostringstream ss;
  ss << "(1,2)\n" << "(1,3)\n" << "(1,4)\n" ;
  cout << ss.str();

  //assign a string to the contents of the ostringstream:
  string rawlines = ss.str();

  //now create an input stringstream with the value of the rawlines
  istringstream iss(rawlines);

  string temp;//just a temporary object used for storage
  vector<string> lines;//this is where your lines will be held

  //now iterate over the stream and store the contents into the vector `lines`:
  while(getline(iss, temp)) {
      lines.push_back(temp);
  }

  //now reverse the contents:
  reverse(lines.begin(), lines.end());

  //see what's inside:
  for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
    cout << *it << endl;
  }

这将打印:
(1,4)
(1,3)
(1,2)

如预期的

注意:这会从原始字符串中删除换行符。
并且,这要求:
//for `getline`:
#include <cstdlib>
//for `reverse`:
#include <algorithm>
//for `string`:
#include <string>
//for `vector`:
#include <vector>

关于c++ - 逐行反转ostringstream,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18937511/

10-11 18:59