Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is getline so inconsistent?

I am at the computer lab and none of the tutors can figure out why my getline is not working correctly. It is not storing the information correctly (only stores 1 or 2 letters). Does anyone know why this is so?

void addMovie(Inventory movie[], int &count)
{
    string s;
    int i;

    cout << "Please enter the SKU " << endl;
    cin >> i;
    movie[count].sku = i;

    cout << "Please enter the name of the movie you wish to add " << endl;

    cin.ignore('\n');
    getline(cin, s, '\n');
    movie[count].title = s;

    count++;
}
like image 959
David Salazar Avatar asked Sep 19 '12 00:09

David Salazar


1 Answers

std::istream::ignore (i.e. cin.ignore())'s first argument is the number of characters to discard. The value of '\n' has an ASCII code of 10, so that '\n' is being implicitly converted to an integer (most likely 10, but it could differ if a different encoding is used - EBCDIC uses 21), and that's how many characters are being ignored, leaving a few left over.

What you actually want is to discard the maximum possible number until you find a newline:

#include <limits> //for numeric_limtis
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
like image 70
chris Avatar answered Sep 18 '22 00:09

chris