2014-05-03 41 views
1

我想輸入一個字符串(與之間的空格),我正在使用cin.getline()。但我得到一個運行時錯誤(循環執行無限)。我如何輸入字符串與空格?

class account 
{ 
     int acno; 
     int password; 
     char name[50]; 
     char address[100]; 
     char sex; 
     string phonenumber; 
    public: 
     void create_account(); //function to get data from user 
     void show_account() const; //function to show data on screen 
     void modify(); //function to add new data 
     void withdraw(int,int); //function to accept amount and subtract from balance amount 
     void donate(int,int); //function to accept amount and add to balance amount 
     void report() const; //function to show data in tabular format 
     int retacno() const; //function to return account number 
     int retpassword() const; //function to return password 
}; // class definition 

這是我輸入班級記錄數據的函數。

void account::create_account() 
{ 
    cout<<"\nEnter The account No. :"; 
    cin>>acno; 
    cout<<"\n\nEnter The Name of The account Holder : "; 
    cin.getline(name,49); 
    cin.ignore(); 
    cout<<"\n\nEnter your Password (Max 8 characters) : "; 
    cin>>password; 
    cin.ignore(); 
    cout<<"\n\nEnter your Address : "; 
    cin.getline(address,99); 
    cin.ignore(); 
    cout<<"\nEnter your Contact Number: "; 
    cin>>phonenumber; 
    cin.ignore(); 
    cout<<"\nSex (Enter M for male and F for female): "; 
    cin>>sex; 
    cout<<"\n\n\nAccount Created..\n\n"; 
} 

當我執行此我得到一個運行時錯誤,如果我在字符串條目之間 引進空間,它跳過字符串輸入,如果我不使用cin.ignore()函數。

+0

可能相關:http://stackoverflow.com/questions/23047052/why-does-reading-a-struct-record-fields-from-stdistream-fail-and-how-can-i-fi –

+0

如果你需要在char數組中輸入一個帶空格的字符串(如你的例子),你可以使用「fgets」函數。 但是,最好使用'std :: string'類而不是char數組和輸入字符串,使用帶有2個參數的「getline」函數:輸入流和輸入字符串。例如。 getline(cin,str);' – Kirill

回答

4

使用獨立式std::getline功能,不是的成員函數。前者在std::string上運行,所以你不必亂搞原始指針。

相關問題