开发者

Problem in accepting a blank space to string in c++

开发者 https://www.devze.com 2023-02-26 00:41 出处:网络
I wrote this code to obtain name. telephone and address of a person and then i input these into class object variables:

I wrote this code to obtain name. telephone and address of a person and then i input these into class object variables:

#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;
}

However If I enter the name separated with its surname, the code bypasses the next cins and exits. Can some one help me out why this happens? Same happens when I enter 10 digit cell no. Thanks in advance


Use std::getline() instead of operator>> to extract a std::string containing whitespace.

0

精彩评论

暂无评论...
验证码 换一张
取 消