0

I'm new in C++. I create a project that ask user to input their name, age, handphone number and university.

The code seems like this:

#include<iostream>
#include<iomanip>
#include<vector>

using namespace std;

int main(){
vector<string>name;
vector<string>age;
vector<string>hpno;
vector<string>university;

string sname, sage, shpno, suniversity;

cout << "Enter name:" << endl;
getline(cin, sname);
name.push_back(sname);

cout << "Enter age:" << endl;
getline(cin, sage);
age.push_back(sage); 

cout << "Enter phone number:" << endl;
getline(cin, shpno);
hpno.push_back(shpno);

cout << "Enter university:" << endl;
getline(cin, suniversity);
university.push_back(suniversity);

cout << "Name" <<" "<< "Age" <<" "<< "Handphone Number" <<" "<< "University" 
     <<endl;    

for (int j = 0 ; j <= name.size() - 1 ; j++){
cout << name[j] << " " << age[j] << " " << hpno[j] << " " << 
university[j]<<endl;}

}

Let say the user input is like this:

Name: John Cena
Age: 20
Phone Number: 1234568903
University: Multimedia Univeristy

The Output that I want is like this:
Name Age Phone Number University John Cena 20 1234568903 Multimedia University


But the Output that I get is like this:
Name Age Phone Number University John Cena 20 1234568903 Multimedia University

How to make the width of header synchronize with the width of content ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

2

I think you should set the width. For that in c++, there is setw(). use that

http://www.c4learn.com/cplusplus/cpp-setw-setting-field-width/

follow this link

Harish Mahajan
  • 3,254
  • 4
  • 27
  • 49
1

First include the missing <string> header, don't rely on free rides from other headers. Then utilize the std::left and std::setw stream manipulators on both the title and the data output:

std::cout << std::left << std::setw(10) << "Name"
    << std::setw(10) << "Age"
    << std::setw(20) << "Handphone Number"
    << std::setw(10) << "University"
    << std::endl;

for (int j = 0; j <= name.size() - 1; j++){
    cout << std::setw(10) << name[j]
        << std::setw(10) << age[j] 
        << std::setw(20) << hpno[j] 
        << std::setw(10) << university[j] << endl;
}

Note: some manipulators are persistent and need to be included only once, others are not and need to be included multiple times. Avoid the using namespace std.

Ron
  • 14,674
  • 4
  • 34
  • 47
0

In this case you need std::setw(), std::setfill('*'). Follow this links and read documentation.

http://www.cplusplus.com/forum/beginner/29761/

http://www.cplusplus.com/reference/ios/right/

C++ can setw and setfill pad the end of a string?

Tazo leladze
  • 1,430
  • 1
  • 16
  • 27