Can't for the life of me get this to align in C++
been trying to get this to align, and every source has told me to use left and setw, but no matter how I format it I can't seem to get it to work. Anyone have any ideas?
#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; } }
This is the output:
able massive 12 g
beehive josh 213 a
cereal open 124 s
pub nab 123 p
deck itch 55 e
setw
sets the width of the next output. It does not retroactively change how previous output is formatted. Instead of ... << someoutput << setw(width)
you want ... << 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;
}
}
Live:
able massive 12 g
beehive josh 213 a
cereal open 124 s
pub nab 123 p
deck itch 55 e