一直試圖讓它對齊,每個訊息來源都告訴我使用 left 和 setw,但無論我如何格式化它,我似乎都無法讓它作業。有人有想法么?
#include <iostream>
#include <string>
#include <iomanip> using namespace std;
int main() { string name[5] = {"able", "beehive", "cereal", "pub", "deck"}; string lastName[5] = {"massive", "josh", "open", "nab", "itch"}; float score[5] = {12, 213, 124, 123, 55}; char grade[5] = {'g', 'a', 's', 'p', 'e'}; int counter = 5; for (int i = 0; i < counter; i ){
cout << left
<< name[i] << " " << setw(15) << left
<< lastName[i] << setw(15) << left
<< score[i] << setw(20)
<< grade[i]; cout << endl; } }
這是輸出:
able massive 12 g
beehive josh 213 a
cereal open 124 s
pub nab 123 p
deck itch 55 e
uj5u.com熱心網友回復:
setw設定下一個輸出的寬度。它不會追溯更改先前輸出的格式。而不是... << someoutput << setw(width)你想要的... << setw(width) << someoutput:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
string name[5] = {"able", "beehive", "cereal", "pub", "deck"};
string lastName[5] = {"massive", "josh", "open", "nab", "itch"};
float score[5] = {12, 213, 124, 123, 55};
char grade[5] = {'g', 'a', 's', 'p', 'e'};
int counter = 5;
for (int i = 0; i < counter; i ){
cout << left << " " << setw(15) << left << name[i]
<< setw(15) << left << lastName[i]
<< setw(20) << score[i]
<< grade[i];
cout << endl;
}
}
直播:
able massive 12 g
beehive josh 213 a
cereal open 124 s
pub nab 123 p
deck itch 55 e
uj5u.com熱心網友回復:
這是您的代碼,經過一些重構:
#include <iostream>
#include <iomanip>
#include <string>
#include <array>
int main( )
{
// use std::array instead of antiquated raw arrays, it does
// the same job but more conveniently
// also use value initialization like `{ }` instead of this `= { }`
std::array<std::string, 5> name { "able", "beehive", "cereal", "pub", "deck" };
std::array<std::string,5> lastName { "massive", "josh", "open", "nab", "itch" };
std::array<float, 5> score { 12, 213, 124, 123, 55 };
std::array<char, 5> grade { 'g', 'a', 's', 'p', 'e' };
constexpr std::size_t counter { name.size( ) }; // `counter` can be a
// constant expression so
// declare it constexpr
for ( std::size_t idx { }; idx < counter; idx ) // std::size_t for the
{ // loop counters
std::cout << std::left << ' '
<< std::setw(15) << std::left << name[idx]
<< std::setw(15) << std::left << lastName[idx]
<< std::setw(20) << std::left << score[idx]
<< std::setw(1) << std::left << grade[idx];
std::cout << '\n';
}
}
輸出:
able massive 12 g
beehive josh 213 a
cereal open 124 s
pub nab 123 p
deck itch 55 e
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414911.html
標籤:
