要知道第一线的压痕,您需要知道输入中的行数。因此你必须先读入所有的输入。为了便于使用.size()成员函数,我选择使用矢量来存储值,该函数将在读入所有输入后给出总行数。
#include<iostream>
#include<sstream>
#include<vector>
#include<iomanip> // For setw
using namespace std;
int main()
{
stringstream ss;
vector<string> lines;
string s;
//Read all of the lines into a vector
while(getline(cin,s))
lines.push_back(s);
// setw() - sets the width of the line being output
// right - specifies that the output should be right justified
for(int i=0,sz=lines.size();i<sz;++i)
ss << setw((sz - i) + lines[i].length()) << right << lines[i] << endl;
cout << ss.str();
return 0;
}
在这个例子中,我使用setw来设置行的宽度是右对齐的。字符串左边的填充由(sz - i)给出,其中sz是行的总数,i是当前行。因此,每个后续行在左侧的空间都减少了一个。
接下来,我需要添加行的原始大小(lines [i] .length()),否则行将不会包含足够大的空间,以便生成的字符串在左侧具有正确的填充侧。
setw((sz - i) + lines[i].length())
希望这有助于!
http://www.cplusplus.com/reference/iostream/manipulators/setw/看看这个 – v01d
只是要清楚,你计算自己的价值和打印?还是你解析它们然后重新打印? – Benj
我自己计算它们,我会看看setw,似乎是一个不错的方法:-) – AnatraIlDuck