2012-10-25 72 views
0

我已經做了兩個星期的C++了,我創建了一個非常簡單的程序,它允許用戶輸入他們的名字,然後輸出那裏的全名,這裏是代碼;C++ help - getline

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    string first ; 
    string middle ; 
    string last; 

    cout << "What is your firstname?" << endl; 
    getline(cin, first); 
    cout << "Your firstname is "; 
    first = first; 
    cout << first << endl; 
    cout << endl; 

    cout << "What is your middle name?" << endl; 
    getline(cin, middle); 
    cout << "Your middle name is "; 
    middle = middle; 
    cout << middle << endl; 
    cout << endl; 

    cout << "What is your lastname?" << endl; 
    getline(cin, last); 
    cout << "Your lastname is "; 
    last = last; 
    cout << last << endl; 
    cout << endl; 

    cout << "Your full name is " << first + middle + last << endl; 

    system ("pause"); 
    return 0; 
} 

我遇到的問題是,它會在最後COUT

cout << "Your full name is " << first + middle + last << endl; 

不輸出空格任何幫助,將不勝感激! 謝謝。

+1

嗯,你不告訴打印任何空格,爲什麼? – Mat

+0

我該怎麼做? –

+1

這就是你想要做的:'cout <<「你的全名是」<< first <<「」<< middle <<「<< << last << endl;' – Zane

回答

3

你的輸出線改爲

cout << "Your full name is " << first << " " << middle << " " << last << endl; 
+0

啊完美,謝謝! –

+0

這不正是Zane所建議的,但OP說它看起來不整潔?我很困惑。 –

+1

(只是爲了澄清,+1,因爲這是給予C++ 2周經驗的適當答案。) –

0

那是因爲你沒有告訴它來寫,我想你想他們的空間。

我的猜測是,你的空間就在

"Your full name is " 

然後你想你firstmiddlelast字符串之間無空格罰款? 但是你永遠不會在那裏添加任何空格。

,看起來像

<< first + middle + last << 

必須改變,以包含空格的部分

<< first + " " + middle + " " + last << 

所以,你在最後整個COUT應該

cout << "Your full name is " << first + " " + middle + " " + last << endl; 
0
#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    string first ; 
    string middle ; 
    string last; 

    cout << "What is your firstname?\n"; 
    getline(cin, first); 
    cout << "Your firstname is " << first << "\n\n"; 

    cout << "What is your middle name?\n"; 
    getline(cin, middle); 
    cout << "Your middle name is " << middle << "\n\n"; 

    cout << "What is your lastname?\n"; 
    getline(cin, last); 
    cout << "Your lastname is " << last << "\n\n"; 

    cout << "Your full name is " << first +" "+ middle +" "+ last << "\n\n"; 

    system ("pause"); 
    return 0; 
}