Ana*_*uck 6 c++ stringstream getline centering
我正在学习c ++并且得到了一个项目来发送一个pascal的三角形输出(在n行计算之后).得到这样的输出,存储在一个字符串流"缓冲区"中
1
1 1
1 2 1
1 3 3 1
Run Code Online (Sandbox Code Playgroud)
但我想要的是相当的
1
1 1
1 2 1
1 3 3 1
Run Code Online (Sandbox Code Playgroud)
我的想法是:计算最后一行和当前行长度的差异(我知道最后一行是最长的).然后使用空格填充每一行(行长度差的一半).我现在的问题是:
不知怎的,我觉得我没有使用stringstream的最佳方式.
所以这是一个很常见的问题:如何解决这个问题,如果可能的话,使用stringstreams - 怎么样?
要知道第一行的缩进,您需要知道输入中的行数。因此,您必须首先读入所有输入。我选择使用向量来存储值,以方便 .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;
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,我使用 setw 将线的宽度设置为右对齐。字符串左侧的填充由 (sz - i) 给出,其中 sz 是总行数,i 是当前行。因此,后续的每一行左侧的空间都会减少 1。
接下来,我需要添加行的原始大小 (lines[i].length()),否则该行将不会包含足够大的空间,以便生成的字符串在左侧具有正确的填充。
setw((sz - i) + lines[i].length())
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!