Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic parametrized constructor issue in C++

I am here including a simple program that written in C++ where I am trying to use a parametrized constructor. My idea is to instantiate the class dynamically and capture the required task. But whenever I run the program and enter the task 1 it simply prints the two lines (i.e. Enter Name.Enter Tel.No.). It is actually supposed to print "Enter Name." then input the name, And then again print "Enter Tel.No.". How can I fix the issue? I have to use parametrized constructor dynamically while 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();
     }
like image 949
TRN 7 Avatar asked Jan 15 '23 20:01

TRN 7


1 Answers

You are using cin >> myTask to read the first input. As you press enter to give the 1, selecting "Add Record", that 1 will be read from the buffer, but your newline will still be in the input buffer. Thus, the first getline will only read this off the buffer, producing an empty input for the line getline(cin, fullname);

like image 151
Agentlien Avatar answered Jan 26 '23 06:01

Agentlien