【问题标题】:use of cin and getline are causing errors [duplicate]使用 cin 和 getline 导致错误[重复]
【发布时间】:2021-08-26 09:47:48
【问题描述】:

在下面的代码中,我做了两个类,第二个类继承自第一个类。但是,当我调用 getdata 函数时。它跳过输入,我尝试使用 cin.ingnore() 和 cin>>ws,但我仍然遇到相同的错误。它运行正常,直到“输入姓氏”,但之后,它只打印所有其他内容而不接受输入。

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

class RegistrationModule{
    protected:
        string Firstname;
        string Lastname;
        double cnic;
        double contact;
        string address;
        static double challanno;
        
        public:
            RegistrationModule(){
                Firstname = "";
                Lastname = "";
                cnic=0;
                address = "";
                contact=0;
                challanno++;
            }
};
double RegistrationModule::challanno=105487;
class monthlyentry : public RegistrationModule{
    public:
        void getdata(){
            cout<<"Enter First Name"<<endl;
            getline(cin,Firstname);
            cin.ignore();
            cout<<"Enter Last Name"<<endl;
            getline(cin,Lastname);
            cin.ignore();
            cout<<"Enter your CNIC: "<<endl;
            cin>>cnic;
            cin.ignore();
            cout<<"Enter your Address: "<<endl;
            getline(cin,address);
            cout<<"Enter your contact number: "<<endl;
            cin>>contact;
            cout<<"Your Challan Number is: "<<challanno<<endl;
        }
};

int main(){
    int size;
    monthlyentry a;
    a.getdata(); 
}

【问题讨论】:

标签: c++ class oop inheritance


【解决方案1】:

你不能随便打ignore() 并期望一切正常。默认情况下,ignore() 将删除 1 个字符。如果那里没有字符,它将设置 eof() 位,并且您的流无法读取更多内容,直到您从中 clear() eof 标志。

只有在有剩余的行尾时才使用ignore()(例如在格式化提取之后)。

    void getdata(){
        cout<<"Enter First Name"<<endl;
        getline(cin,Firstname);

        cout<<"Enter Last Name"<<endl;
        getline(cin,Lastname);

        cout<<"Enter your CNIC: "<<endl;
        cin>>cnic;
        cin.ignore();

        cout<<"Enter your Address: "<<endl;
        getline(cin,address);

        cout<<"Enter your contact number: "<<endl;
        cin>>contact;
        cin.ignore(); // might want to clear up before next extractions

        cout<<"Your Challan Number is: "<<challanno<<endl;
    }

要使用std::ws,您需要直接在 getline 调用中使用

std::getline(std::cin >> std::ws, Firstname);

【讨论】:

    猜你喜欢
    • 2017-03-07
    • 2015-12-04
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多