[英]How to use setw and setfill together in C++ to pad with blanks AND chars?
[英]C++ can setw and setfill pad the end of a string?
有沒有辦法讓setw
和setfill
填充字符串的末尾而不是前面?
我有一種情況,我打印這樣的東西。
CONSTANT TEXT variablesizeName1 .....:number1
CONSTANT TEXT varsizeName2 ..........:number2
我想添加一個可變數量的'.'
到了最后
"CONSTANT TEXT variablesizeName#"
所以我可以在屏幕上輸出":number#"
。
注意:我有一個"variablesizeName#"
數組,所以我知道最廣泛的情況。
要么
我應該通過這樣設置setw
手動完成
for( int x= 0; x < ARRAYSIZE; x++)
{
string temp = string("CONSTANT TEXT ")+variabletext[x];
cout << temp;
cout << setw(MAXWIDTH - temp.length) << setfill('.') <<":";
cout << Number<<"\n";
}
我想這可以做到這一點,但感覺有點笨重。
想法?
您可以使用操縱符std::left
, std::right
和std::internal
來選擇填充字符的位置。
對於您的具體情況,這樣的事情可以做:
#include <iostream>
#include <iomanip>
#include <string>
const char* C_TEXT = "Constant text ";
const size_t MAXWIDTH = 10;
void print(const std::string& var_text, int num)
{
std::cout << C_TEXT
// align output to left, fill goes to right
<< std::left << std::setw(MAXWIDTH) << std::setfill('.')
<< var_text << ": " << num << '\n';
}
int main()
{
print("1234567890", 42);
print("12345", 101);
}
輸出:
Constant text 1234567890: 42
Constant text 12345.....: 101
編輯 :如鏈接中所述, std::internal
僅適用於整數,浮點和貨幣輸出。 例如,對於負整數,它將在負號和最左側數字之間插入填充字符。
這個:
int32_t i = -1;
std::cout << std::internal
<< std::setfill('0')
<< std::setw(11) // max 10 digits + negative sign
<< i << '\n';
i = -123;
std::cout << std::internal
<< std::setfill('0')
<< std::setw(11)
<< i;
將輸出
-0000000001
-0000000123
就像是:
cout << left << setw(MAXWIDTH) << setfill('.') << temp << ':' << Number << endl;
產生類似的東西:
derp..........................:234
herpderpborp..................:12345678
#include <iostream>
#include <iomanip>
int main()
{
std::cout
<< std::setiosflags(std::ios::left) // left align this section
<< std::setw(30) // within a max of 30 characters
<< std::setfill('.') // fill with .
<< "Hello World!"
<< "\n";
}
//Output:
Hello World!..................
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.