空格不能用在字符串中?C++

OVE*_*ONE 3 c++ string cin

基本上我正在尝试多态性.我有2个对象,一个客户和一个员工.客户有姓名和投诉.员工有姓名和薪水.

在循环中,我接受这些参数并创建一个新的Person来添加到数组中.

但这是我的问题:如果我在字符串中放置任何空格,那么循环就会结束.

Person *persons[10];

for (int i = 0; i < sizeof persons;i++)
{
    cout<<"Please type 1 for customer or 2 for Employee"<<endl;
    int q;
    cin>>q;
    string name;
    int salary;
    string complaint;


    if (q == 1)
    {
        cout<<"What is your name?"<<endl;
        cin>>name;
        cout<<"What is your complaint"<<endl;
        cin>>complaint;

        personPtr = new Customer(name,complaint);
        cout<<"Created customer"<<endl<<endl;
        persons[i] = personPtr;
        cout<< "added to array"<<endl<<endl;
    }
    else if(q==2)
    {
        cout<<"What is your name?"<<endl;
        cin>>name;
        cout<<"What is your salary"<<endl;
        cin>>salary;
        personPtr = new Employee(name,salary);
        persons[i] = personPtr;
    }
    else
    {
        cout<<"Sorry but i could not understand your input. Please try again"<<endl;
        i--;
        cin>>q;
    }
}
delete personPtr;
system("PAUSE");
Run Code Online (Sandbox Code Playgroud)

有没有特殊的方法来包含字符串?

这是客户和员工类供参考.

class Person
{
public:
Person(const string n)
{name = n;}; // initialise the name
virtual void printName();
protected:
string name;
};


class Customer:public Person
{
public:
string complaint;

Customer(string name, string cm)
    :Person(name)
{       
    complaint=cm;
}
virtual void printName();
};

class Employee:public Person
{
public:
int salary;

Employee(string name,int sl)
    :Person(name)
{       
    salary = sl;
}
virtual void printName();
};
Run Code Online (Sandbox Code Playgroud)

sbi*_*sbi 8

  1. 输入操作符

    std::istream& operator>>(std::istream& is, std::string&)
    
    Run Code Online (Sandbox Code Playgroud)

    读取输入到下一个空白字符.(这就是Jerry Schwartz 25年前发明IO流时指定的方式.)如果你需要阅读整,那么

    std::istream& getline(std::istream&, std::string&, char='\n')
    
    Run Code Online (Sandbox Code Playgroud)

    是你需要使用的:

    std::string name;
    std::getline(std::cin, name);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 输入可能会失败.例如,读取int可能会失败,因为输入缓冲区中只有非数字数字.如果流操作失败,则会在流中设置状态位.发生故障后,流不会执行任何进一步的操作.>>然后,操作数将保持不变.
    因此,您需要在使用数据之前检查输入操作是否成功.最简单的方法是在输入操作后检查流:

    if(!std::cin) {
      // input failed
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • @OVERTONE:经过相当长的一段时间之后,我习惯了人们在回答之前对_question_的细节进行了修饰,但对于回答问题的提问者对我来说是新闻._我写的是什么让你认为你需要重载`operator >>`?? _ (4认同)