我如何输入带空格的字符串

How do i input strings with spaces?

本文关键字:字符串 空格 输入带      更新时间:2023-10-16

我想输入一个字符串(中间有空格),我使用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<<"nnEnter The Name of The account Holder : ";
    cin.getline(name,49);
    cin.ignore();
    cout<<"nnEnter your Password (Max 8 characters) : ";
    cin>>password;
    cin.ignore();
    cout<<"nnEnter 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<<"nnnAccount Created..nn";
}

当我执行这个时,如果我在字符串条目之间引入空格,我会得到一个运行时错误如果我不使用cin.ignore()函数,它会跳过字符串输入

使用独立的std::getline函数,而不是成员函数。前者在std::string上操作,因此您不必使用原始指针。