Home > Enterprise >  How to accept empty input in C
How to accept empty input in C

Time:11-12

Accepting user empty input and passing default value from the constructor

I just start learning C . Now I was trying creating a simple requestion header. What I was expected is the "ABC Industries" should be used as a default value for the purchaser name and "XYZ Supplier" should be used as a default for the vendor name.

I created a default constructor and a param constructor. Here is my code:

class Requisition{
    private:
        string purchaser, vendor;
    
    public:
        Requisition()
        :purchaser("ABC Industries"),vendor("XYZ Supplier"){}

        Requisition(string pname, string vname)
        :purchaser(pname),vendor(vname){}

        void getStaffInput(){
            cout << "Enter a purchaser name: ";
                cin>>purchaser;
            cout << "Enter a vendor name: ";
                cin>>vendor;
        }

        void printHeader(){
            cout << "\n********************************************************\nPurchaser: "
                 << purchaser <<"\nVendor: "<<vendor
                 <<"\n********************************************************"<<endl;
        }
};

Here is my question:

  1. How can I accept user inputting a empty string (user direct press enter or spacing) because in C will force to input something to continue.

  2. If user doesn't key in any data, or just inputting either one of the data (purchaser or vendor), How can I pass the default value to the print function?

int main(){
    Requisition req;
    req.getStaffInput();
    req.printHeader();
}

My program output is forcing the user to input something (can't be blank and spacing), the program should accepting those blank or spacing input and get the default value from the default constructor and display it.

Thanks.

CodePudding user response:

cin into a string will read, effectively, one token. The exact rules are complicated, but it basically pulls content until a space or newline. If you don't input any content, it waits until there's something.

You're looking for getline, which reads until the next newline and returns whatever it finds, even if what it finds is nothing at all.

std::getline(std::cin, purchaser);
  •  Tags:  
  • c
  • Related