简体   繁体   English

C ++中的动态参数化构造函数问题

[英]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. 我在这里包括一个用C ++编写的简单程序,我试图使用参数化构造函数。 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 (ie Enter Name.Enter Tel.No.). 但每当我运行程序并输入任务1时,它只会打印两行(即输入Name.Enter Tel.No.)。 It is actually supposed to print "Enter Name." 它实际上应该打印“输入名称”。 then input the name, And then again print "Enter Tel.No.". 然后输入名称,然后再次打印“输入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();
     }

You are using cin >> myTask to read the first input. 您正在使用cin >> myTask来读取第一个输入。 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. 按Enter键给1,选择“Add Record”,将从缓冲区中读取1,但换行符仍然在输入缓冲区中。 Thus, the first getline will only read this off the buffer, producing an empty input for the line getline(cin, fullname); 因此,第一个getline只会从缓冲区中读取这个,为行getline(cin, fullname);产生一个空输入getline(cin, fullname);

The reason is that the first newline after the task type is not consumed by 原因是任务类型之后的第一个换行符未被使用

cin >> myTask

so the fullname reading will only read an empty line and the "enter Tel.No" thing will be printed directly. 所以fullname读取只会读取一个空行,“输入Tel.No”的东西将直接打印。

Insert a getline call after the cin >> myTask to fix this problem. cin >> myTask之后插入一个getline调用来解决这个问题。

Also see this question . 另见这个问题

This probably has nothing to do with your constructor, but rather with the mixing of cin >> and getline. 这可能与你的构造函数无关,而是与cin >>和getline的混合。 Add a getline to a garbage variable after cin >> myTask and it should work. 在cin >> myTask之后为垃圾变量添加一个getline,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM