gpt4 book ai didi

c++ - 如何输入带空格的字符串?

转载 作者:行者123 更新时间:2023-11-30 01:53:07 27 4
gpt4 key购买 nike

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

这是我为类(class)记录输入数据的函数。

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() 函数,它会跳过字符串输入。

最佳答案

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

关于c++ - 如何输入带空格的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23448009/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com