0

I want the user to enter a string, double and a long, but the thing is after the first time, the string is kind of being ignored and left empty and prompting for the double directly.

here's my code:

#include <iostream>
#include <string>

using namespace std;

int main () {
    string name;
    double price;
    long serial;

    cout << "Enter the dvd's name: "; getline(cin, name);
    cout << "Enter the dvd's price (in $): "; cin >> price;
    cout << "Enter the dvd's serial number: "; cin >> serial;

    cout << endl;

    cout << "Enter the dvd's name: "; getline(cin, name);
    cout << "Enter the dvd's price (in $): "; cin >> price;
    cout << "Enter the dvd's serial number: "; cin >> serial;

    return 0;
}

the console of the code

as you can see the first time, i can enter a string the second time just sends me directly to the double, and even if i ignored the missing string, and put a double and then a long, it will print name as empty string.

What is wrong with my code?

hakuna matata
  • 3,243
  • 13
  • 56
  • 93

2 Answers2

1

The whitespace (carriage returns or space) after the serial number is not retrieved, and the getline then picks it up.

Edit: As johnathon points out, cin >> ws does not work right in this case (I'm sure I used this like this before, though I can't find an example).

Tested Solution: Instead, adding this after the serial number will get the carriage return (and any other whitespace) out of the stream so that it is ready for the next DVD name.

string dummy;
getline(cin, dummy);
crashmstr
  • 28,043
  • 9
  • 61
  • 79
  • 1
    it's not the whitespace that's getting him it's the carrage returns – johnathan May 10 '12 at 18:01
  • Those are whitepspace too. the `ws` manipulator will take in any whitepsace, which includes spaces, tabs, newlines, and carriage returns. – crashmstr May 10 '12 at 18:37
  • just to note, cin >> ws; prevents his code from advancing beyond that point, cin.ignore(2,'\n') works though. – johnathan May 10 '12 at 20:52
1

I generally use istringstream in such cases (as shown below). But a better solution would be to use cin.ignore

#include <sstream>

int main () {
    string name,line;
    double price;
    long serial;

    cout << "Enter the dvd's name: "; getline(cin, line);
    name = line;
    cout << "Enter the dvd's price (in $): ";
    getline(cin,line);
    istringstream(line)>>price;
    cout << "Enter the dvd's serial number: ";
    getline(cin,line);
    istringstream(line)>>serial;
    cout << endl;
    return 0;

}

Abhishek Iyer
  • 604
  • 2
  • 6
  • 18