dimanche 14 juin 2020

Alternatives of getline

#include <iostream>
using namespace std;

class publication {
private:
  string title;
  float price;

public:
  publication() {
    this->title = "";
    this->price = 0.0;
  }

  void getdata() {
    cout << "Enter Title: ";
    getline(cin, title);
    cout << "Enter price: ";
    cin >> this->price;
  }

  void putdata() {
    cout << "Title: " << title << endl;
    cout << "Price: " << price << endl;
  }
};

class book : public publication {
private:
  int pageCount;

public:
  book() { this->pageCount = 0; }

  void getdata() {
    publication::getdata();
    cout << "Enter page count: ";
    cin >> pageCount;
  }

  void putdata() {
    publication::putdata();
    cout << "Page Count: " << pageCount << " pages\n";
  }
};

class tape : public publication {
private:
  float playingTime;

public:
  tape() { this->playingTime = 0; }

  void getdata() {
    publication::getdata();
    cout << "Enter playing time: ";
    cin >> playingTime;
  }

  void putdata() {
    publication::putdata();
    cout << "Playing Time: " << playingTime << " mins\n";
  }
};

int main() {
  book b;
  tape t;
  b.getdata();
  t.getdata();
  b.putdata();
  t.putdata();
  return 0;
}

The first time getline() works perfectly, but the second time it's called, it gets skipped because of some cin >> value; has executed before it. I tried adding a cin.ignore() before getline(), but it either requires me to press enter before giving an input, or skips the first character of the first input.

However, if I add cin.ignore() after the end of every cin >> value; block, it works.

So so I have to suddenly add cin.ignore() everywhere because of one getline()? Or is there any alternative for getline() to take spaces as input?

1 commentaire:

  1. https://codereview.stackexchange.com/questions/124194/user-registration-and-login-program

    I learn the code and apply it to my program.

    RépondreSupprimer