2011-04-15 46 views
0

我寫了這個代碼來獲取名稱。電話和一個人的地址,然後我輸入到這些類對象變量:問題在接受C++中的字符串的空格

#include<iostream> 
#include<cstdlib> 
#include<fstream> 
#include<string> 
using namespace std; 

class contact{ 
public: 
    string name;//ALL CLASS VARIABLES ARE PUBLIC 
    unsigned int phonenumber; 
    string address; 

    contact(){//Constructor 
     name= "Noname"; 
     phonenumber= 0; 
     address= "Noaddress"; 
    } 

    /*void input_contact_name(string s){//function to take contact name 
     name=s; 
    } 
    void input_contact_number(int x){//function to take contact number 
     phonenumber=x; 
    } 
    void input_contact_address(string add){//function to take contact address 
     address=add; 
    }*/ 
}; 

int main(){ 
    contact *d; 
    d= new contact[200]; 
    string name,add; 
    int choice;//Variable for switch statement 
    unsigned int phno; 
    static int i=0;//i is declared as a static int variable 
    bool flag=false; 
    cout<<"\tWelcome to the phone Directory\n";//Welcome Message 
    cout<<"Select :\n1.Add New Contact\n2.Update Existing Contact\n3.Delete an Existing Entry\n4.Display All Contacts\n5.Search for a contact\n6.Exit PhoneBook\n\n\n";//Display all options 
    cin>>choice;//Input Choice from user 
    while(!flag){//While Loop Starts 
     switch(choice){//Switch Loop Starts 
     case 1: 
      cout<<"\nEnter The Name\n"; 
      cin>>name; 

      d[i].name=name; 
      cout<<"\nEnter the Phone Number\n"; 
      cin>>phno; 
      d[i].phonenumber=phno; 
      cout<<"\nEnter the address\n"; 
      cin>>add; 
      d[i].address=add; 
      i++; 

      flag=true; 
     } 
    } 
    return 0; 
} 

但是如果我進入其姓分離的名稱,代碼繞過下一CINS並退出。有人能幫我解釋爲什麼會發生這種情況嗎? 當我輸入10位數字單元號時,會發生同樣的情況。 在此先感謝

+1

請付出一些努力來格式化您的代碼。發佈較短的樣本也是一個好主意。 – Mat 2011-04-15 10:09:26

+0

謝謝你,我會在將來記住這一點:D – 2011-04-15 10:13:45

+0

我建議你接受ildjarn給出的答案。已經有一段時間了,這是正確的答案。 – Mephane 2011-06-08 07:42:47

回答

6

使用std::getline()而不是operator>>來提取包含空格的std::string

+0

我想知道運算符>>和帶空格的字符串是什麼問題? – 2011-04-15 10:23:08

+3

'operator >>'讀取一個元素。通常情況下,一個元素被認爲是由下一個空白字符來終止,就像std :: string和所有基元一樣。正如答案所說,「std :: getline」是你的朋友。 – Mephane 2011-04-15 11:02:10