Проблема в принятии пустого пространства для строки в C ++ - PullRequest
0 голосов
/ 15 апреля 2011

Я написал этот код для получения имени. телефон и адрес человека, а затем я ввожу их в переменные объекта класса:

#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 Ответ

6 голосов
/ 15 апреля 2011

Используйте std::getline() вместо operator>> для извлечения std::string, содержащего пробелы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...