字符串格式化(c ++) [英] String formatting (c++)
问题描述
我尝试在控制台应用程序中格式化输出字符串(如表格)
cout< \\\
\\\
----------------- \\\
;
cout<< setw(8)<<左< F\t |;
cout<< setw(8)<<左< x\t |;
cout<< \\\
----------------- \\\
;
// ...
cout.width(8);
cout.setf(ios :: left);
cout<<固定< setprecision(3)<< F<< \t |;
cout.width(8);
cout.setf(ios :: left);
cout<< x < \t |;
cout<< \\\
----------------- \\\
\\\
;
但结果我的输出看起来像这样
我的上部字符串格式有什么问题?
我会不是
em>停止只是删除选项卡。因为它现在,你的代码是高度重复的,接近不可能维护。我会做一个(几乎)完全重写,有几个功能,以减少重复。我的第一个剪切可能看起来像这样: //在指定宽度的字段中格式化一个值,
template< class T>
string字段(T val,int w,char sep ='|'){
stringstream b;
b<< setw(w)左<固定< setprecision(3)<< val<< sep;
return b.str();
}
//为指定数量的字段生成分隔符
//每个指定宽度
string sep(int c,int w,char val =' - '){
string s(c *(w + 1),val);
return string(\\\
)+ s +\\\
;
}
int main(){
static const int w = 8;
double F = 1.234,x = 3.45;
string s = sep(2,w);
cout<< \\\
< s;
cout<<字段(F,w)<字段(x,w) s;
cout<<字段(F,w)字段(x,w) s;
}
看起来这让代码更容易阅读,可维护。例如,如果我们决定在下一行显示 a
和 b
例如:
cout<字段(a,w)字段(b,w) s;
...我们不必看起来很难以确定它会匹配上一行。同样,如果我们想更改列宽等,
I tried to format output strings in my console application (like a table)
cout << "\n\n-----------------\n";
cout << setw(8) << left << "F\t|";
cout << setw(8) << left << "x\t|";
cout << "\n-----------------\n";
//...
cout.width(8);
cout.setf(ios::left);
cout << fixed << setprecision(3) << F << "\t|";
cout.width(8);
cout.setf(ios::left);
cout << x << "\t|";
cout << "\n-----------------\n\n";
But as result my output looks like this
What's wrong with my upper string formatting?
As already noted, it's the tabs that are causing the problem.
I would not stop at just removing the tabs though. As it stands right now, your code is highly repetitive and next to impossible to maintain. I'd do a (nearly) complete rewrite, with a couple of functions to cut down on the repetition. My first cut would probably look something like this:
// format a value in a field of specified width, followed by a separator
template <class T>
string field(T val, int w, char sep = '|') {
stringstream b;
b << setw(w) << left << fixed << setprecision(3) << val << sep;
return b.str();
}
// generate a separator for a specified number of fields,
// each of a specified width
string sep(int c, int w, char val = '-') {
string s(c * (w + 1), val);
return string("\n") + s + "\n";
}
int main() {
static const int w = 8;
double F = 1.234, x = 3.45;
string s = sep(2, w);
cout << "\n" << s;
cout << field("F", w) << field("x", w) << s;
cout << field(F, w) << field(x, w) << s;
}
Seems to me that this makes the code rather more readable and quite a bit more maintainable. For example, if we decided to display an a
and b
on the next line, it would seem fairly obvious to add something like:
cout << field(a, w) << field(b, w) << s;
...and we wouldn't have to look very hard to be pretty sure it was going to match up with the previous line. Likewise, if we wanted to change a column width, etc.
这篇关于字符串格式化(c ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!