Constructor problem with dynamic parameterization in C ++

I am here, including a simple program written in C ++, where I am trying to use a parameterized constructor. My idea is to dynamically create a class and complete the required task. But whenever I run the program and enter task 1, it just prints two lines (i.e. Enter Name.Enter Tel.No.). In fact, it is supposed to print "Enter Name". then enter the name, and then type "Enter Tel.No." again. How can I fix the problem? I have to use a parameterized constructor dynamically when creating an object.

#include <iostream> #include <conio.h> #include <fstream> #include <string> using namespace std; class myClass { string fullname,telephone; public: myClass(int taskType = 2) { if(taskType==1) { add_record(); } else if(taskType==2) { //view_records(); } else if(taskType==3) { //delete_record(); }else{ // custom_error(); } } void add_record() { cout << "Enter Name.\n"; getline(cin, fullname); cout << "Enter Tel. No.\n"; getline(cin, telephone); } }; main (){ int myTask; cout << "Enter a Task-Type. \n" << "1 = Add Record," << "2 = View Records," << "3 = Delete a Record\n\n"; cin >> myTask; myClass myObject(myTask); getch(); } 
+4
source share
3 answers

This probably has nothing to do with your constructor, but rather a mixture of cin β†’ and getline. Add getline to the garbage variable after cin -> myTask and it should work.

+2
source

You use cin >> myTask to read the first input. When you press enter to give 1, select β€œAdd record” so that 1 is read from the buffer, but your new line will still be in the input buffer. Thus, the first getline will only read this from the buffer, creating an empty input for the string getline(cin, fullname);

+4
source

The reason is that the first line of a new line after the task type is not consumed

 cin >> myTask 

therefore, reading fullname will only read an empty line, and the text "enter Tel.No" will be printed directly.

Insert a getline call after cin >> myTask to fix this problem.

Also see this question .

+3
source

All Articles