Menu

I think this is a bug.

2009-02-04
2012-09-26
  • nguyen nguyen

    nguyen nguyen - 2009-02-04

    include <iostream>

    include <string>

    using namespace std;

    int main ()
    {
    string c;
    double a,b(10);

    cout << "Enter a number. ";
    cin >> a;
    a+=b;
    cout << "The Sum of the number and 10 is " << a << ".\n\n\n";

    cout << "What is the password?\n";
    getline (cin, c);
    cout << "Now i know " << c << " too!\n";

    system("pause");
    return 0;
    }

    I don't know why the "getline(cin,c):" statement didn't ask me for an input when I ran the program.

    Is there something wrong with the program or is this an actual bug?

     
    • cpns

      cpns - 2009-02-04

      It is a bug... in your code.

      Apply Occam's Razor before shouting 'bug'. Consider how many applications rely on the GNU C++ library, and ask yourself whether your assertion is likely to be plausible.

      Console input is line oriented (you have to enter an whole line by pressing <enter> before the input is processed, but formatted input only consumes the characters necessary to assign the data type passed, so at the line:

      cin >> a;

      the entered data is converted to an integer, but the rest of the line (at least a <newline> character) remains in the buffer. That is what gets assigned to c in the line:

      getline (cin, c);

      i.e. the remainder of teh buffered input from the previous input.

      There are a number of solutions, here's two:

      1) Always use std::getline(), and then use a std::istringstream object rather than std::cin (which is an istream object).

      2) Expunge the buffer with a cin::ignore thus:

      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

      Note solution (2) requires <limits> to be included. Because of the using directive, in your case you can use the shorthand:

      cin.ignore(numeric_limits<streamsize>::max(), '\n');

      but I would not recommend moving the entire std:: namespace to ::, that way is the route to even more hard to fathom bugs.

      Clifford

       
    • nguyen nguyen

      nguyen nguyen - 2009-02-04

      thanks!

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.