Truncating with setw

浪子不回头ぞ 提交于 2019-12-12 04:49:07

问题


Is there a way that I can force setw to truncate?

Say that I want to get the output:

blah blah blee le
bu blah blah blee

Is there a way to make this work:

string foo{"bu blah blah blee le"};

cout << setw(foo.size() - 3) << foo.data() + 3 << setw(foo.size() - 3) << foo << endl;

回答1:


No, not really.

You can switch to unformatted output for this example, though:

assert(foo.size() > 3);
cout.write(&foo[3], foo.size() - 3);
cout.write(&foo[0], foo.size() - 3);



回答2:


Not directly.

In the printf format specifiers, the precision argument could be used to specify the maximum number of characters from a string. In C++, however, you use the substring operator:

std::cout << foo.substr(3) << foo.substr(0, foo.size() - 3) << std::endl;

(Of course, for the first, you could also use foo.c_str() + 3.)



来源:https://stackoverflow.com/questions/27380376/truncating-with-setw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!