2014-11-24 45 views
0

我的程序似乎想爲名稱變量輸入兩個輸入,而不是隻輸入一個東西,然後轉到電話號碼?運行程序時,它有我輸入兩行後名稱?請幫助

我敢肯定它的簡單,但有人可以幫我解決這個問題嗎?這是否與getline有關?

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

//define Car struct 
struct Speaker 
{ 
string name; 
string phoneNumber; 
string emailAddress; 
string theme; 
double fee; 
}; 

Speaker *getSpeaker(); 


int main() 
{ 
Speaker thespeaker; 
thespeaker = *getSpeaker(); 
cout << "The speaker entered is!" << endl; 
cout << thespeaker.name << endl; 
cout << "phone number: " << thespeaker.phoneNumber << endl; 
cout << "email: " << thespeaker.emailAddress << endl; 
cout << "theme: " << thespeaker.theme << endl; 
cout << "fees: " << thespeaker.fee << endl; 
} 

Speaker *getSpeaker() 
{ 
Speaker *theSpeaker; 
theSpeaker = new Speaker; 
cout << "Please enter Speakers information" << endl; 
cout << "name: " ; 
getline(cin, theSpeaker->name); 
cin.ignore(100, '\n'); 
cin.clear(); 
cout << theSpeaker->name; 
cout << "\nphone number: "; 
cin >> theSpeaker->phoneNumber; 
cout << "\nEmail Address: "; 
cin >> theSpeaker->emailAddress; 
cout << "\nTheme: "; 
cin >> theSpeaker->theme; 
cout << "\nFee: "; 
cin >>theSpeaker->fee; 

return theSpeaker; 
} 
+0

這泄漏內存 - 採取了所有的'*'來解決這個問題:)(和變化' - >'來'。 ') – 2014-11-24 05:46:44

回答

1

沒有必要爲cin.ignore(); 簡單地把它寫成:

Speaker *getSpeaker() 
{ 
Speaker *theSpeaker; 
theSpeaker = new Speaker; 
cout << "Please enter Speakers information" << endl; 
cout << "name: " ; 
getline(cin, theSpeaker->name); 
cout << theSpeaker->name; 
cout << "\nphone number: "; 
cin >> theSpeaker->phoneNumber; 
cout << "\nEmail Address: "; 
cin >> theSpeaker->emailAddress; 
cout << "\nTheme: "; 
cin >> theSpeaker->theme; 
cout << "\nFee: "; 
cin >>theSpeaker->fee; 

return theSpeaker; 
} 
相關問題