2013-03-24 50 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;