我有一个任务,我需要输出一个包含歌曲信息的数组。我遇到的问题是格式化输出。我的任务指定了显示的每个字段的长度,但我找不到限制输出的好方法。例如,如果歌曲标题有21个字符但要求是18,我将如何防止它超过指定的18.我正在使用setw()函数来正确地分隔所有内容,但它根本不会限制输出。格式化C++输出列,限制每个字段
0
A
回答
0
可以使用字符串调整一个C++字符串::调整。
// resizing string
#include <iostream>
#include <string>
int main()
{
std::string str ("I like to code in C");
std::cout << str << '\n';
unsigned sz = str.size();
.resize (sz+2,'+');
std::cout << str << '\n'; //I like to code in C++
str.resize (14);
std::cout << str << '\n';//I like to code
return 0;
}
+1
谢谢!这个伎俩。 – 2013-03-24 21:58:33
0
您可以从字符串中获得长度为18个字符的子字符串,然后输出该字符串。
http://www.cplusplus.com/reference/string/string/substr/
例子:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str="We think in generalities, but we live in details.";
if(str.length()<=18) cout << str << endl;
else cout << str.substr(0,15) << "..." << endl;
return 0;
}
0
如果你想原始字符串不被修改。
string test("http://www.cplusplus.com/reference/string/string/substr/");
string str2 = test.substr(0,18);
cout<<str2 <<endl;
如果您不需要测试的其余部分。
string test("http://www.cplusplus.com/reference/string/string/erase/");
test.erase(18); // Make sure you don't go out of bounds here.
cout<<test<<endl;
相关问题
- 1. 格式化程序格式化方法的输出限制?
- 2. C++控制台 - 格式化输出
- 3. 格式化C++控制台输出
- 4. 每个字段的限制
- 5. 格式化输入字段
- 6. 格式化输出C++
- 7. c和格式化输出
- 8. 格式化C#输出
- 9. 格式化输出到列
- 10. 格式化输出:列
- 11. 格式化输出列表
- 12. 限制输出列
- 13. 与出现在特定字段数目格式化输出
- 14. Django表格2限制字段形式
- 15. 格式化输出
- 16. 格式化输出
- 17. 格式化输出
- 18. 重新格式化输入字段
- 19. 格式化文本字段输入
- 20. 格式化控制台输出
- 21. 格式化Rails的控制台输出
- 22. 需要得到格式化输出C#
- 23. 的StreamWriter C#格式化输出
- 24. C#格式化文件的输出?
- 25. 问题格式化输出c + +
- 26. 格式化输出到C++ ostringstream对象
- 27. cakephp字段输入限制
- 28. 格式化输出数字4在每一行
- 29. 使用JMSSerializer格式化输入和输出字段(处理单个属性)
- 30. 限制和格式化JTextfield
只尝试将字符串限制为18个字符也许? – Jona 2013-03-24 21:39:30
你使用的是C++字符串吗?或者const char * s? – 2013-03-24 21:40:51
是的,我试图限制其中一列到18其他人是不同的大小,但如果我能找出一个我可以处理其余的。另外我正在使用C++字符串。 – 2013-03-24 21:45:27