2014-09-26 82 views
2

我希望代碼能夠在輸入名稱時接受全名。我如何讓cin接受空間?如何讓cin接受空格?

當我用空格輸入一個名稱時,結果是假定主題名稱的下一個輸入是姓氏。我怎樣才能解決這個問題?

#include<iostream> 
using namespace std; 

int main() 
{ 
    float mark1, mark2, mark3, mark4; 
    char subject1[25], subject2[25], subject3[25], subject4[25]; 
    char name; 
    float average; 

    cout << "Please enter your name"<< endl; 
    cin >> name; 

    cout << "Please enter the first subject name"<< endl; 
    cin >> subject1; 

    cout << "Please enter the mark for " <<subject1<< endl; 
    cin >>mark1; 

    cout << "Please enter the second subject name"<< endl; 
    cin >> subject2; 

    cout << "Please enter the mark for " <<subject2<< endl; 
    cin >>mark2; 

    cout << "Please enter the third subject name"<< endl; 
    cin >> subject3; 

    cout << "Please enter the mark for " <<subject3<< endl; 
    cin >>mark3; 

    cout << "Please enter the fourth subject name"<< endl; 
    cin >> subject4; 

    cout << "Please enter the mark for " <<subject4<< endl; 
    cin >>mark4; 

    average=(mark1+mark2+mark3+mark4)/4; 

    cout << name << "'s " << subject1<< " mark is " <<mark1 <<", " << subject2<< " mark is " << mark2 <<", " <<subject3 <<" mark is " <<mark3 <<", " <<subject4<< " mark is " <<mark4 <<". His/her average is " <<average<< endl; 

    cout << endl; 

    system("PAUSE"); 
    return 0; 
} 

回答

1

嘗試使用getline(cin, <variable name>)

例如:

string name; 
getline(cin, name); 
cout << name; 

請務必閱讀有關使用函數getline但: getline reference