2013-03-24 26 views
0

我有一个任务,我需要输出一个包含歌曲信息的数组。我遇到的问题是格式化输出。我的任务指定了显示的每个字段的长度,但我找不到限制输出的好方法。例如,如果歌曲标题有21个字符但要求是18,我将如何防止它超过指定的18.我正在使用setw()函数来正确地分隔所有内容,但它根本不会限制输出。格式化C++输出列,限制每个字段

+0

只尝试将字符串限制为18个字符也许? – Jona 2013-03-24 21:39:30

+0

你使用的是C++字符串吗?或者const char * s? – 2013-03-24 21:40:51

+0

是的,我试图限制其中一列到18其他人是不同的大小,但如果我能找出一个我可以处理其余的。另外我正在使用C++字符串。 – 2013-03-24 21:45:27

回答

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;