2017-09-23 69 views
0

我是C++新手。我創建了一個項目,要求用戶輸入他們的姓名,年齡,手機號碼和大學。列自動對齊C++

的代碼看起來是這樣的:

#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;} 

} 

讓說,用戶輸入是這樣的:

名稱:約翰·塞納
年齡:20
電話:1234568903
大學:多媒體大學

,我想輸出是這樣的:
Name Age Phone Number University John Cena 20 1234568903 Multimedia University


但我得到的輸出是這樣的:
Name Age Phone Number University John Cena 20 1234568903 Multimedia University

如何使頭的寬度與內容寬度同步?

回答

1

首先包括失蹤<string>頭,不依賴於其他頭免費乘車。然後,利用雙方的標題和數據輸出std::leftstd::setw流操縱:

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; 
} 

注:有些機械手是持久的,需要納入只有一次,其他人都沒有,需要包括多次。 Avoidusing namespace std