如何用空格输入字符串?

时间:2014-05-03 17:59:04

标签: c++

我想输入一个字符串(中间有空格),我正在使用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()函数,它会跳过字符串输入。

1 个答案:

答案 0 :(得分:4)

使用独立的std::getline功能,成员功能。前者以std::string运行,所以你不必乱用原始指针。