2

Possible Duplicate:
Problem of using cin twice

This code works but not what I intended. Every time I want to enter new salary by pressing 1 the the output at command prompt will become like this:

Comic books             : USD Input error! Salary must be in positive integer.



The code should stop at cout<<"\n\nComic books\t\t: USD "; at line 4 but it just executed with the inner while loop. This is the code:

    double multiplePay =0;

    cout<<"\n\nEnter employee pay for each job";
    while (1){
    cout<<"\n\nComic books\t\t: USD ";
    //cin.get(); if enable, the first user input will be 0. this is not working.

    std::string comic_string;
    double comic_double;
    while (std::getline(std::cin, comic_string))
    {
        std::stringstream ss(comic_string); // check for integer value

        if (ss >> comic_double)
        {
            if (ss.eof())
            {   // Success so get out
                break;
            }
        }

        std::cout << "Input error! Salary must be in positive integer.\n" << std::endl;
        cout<<"Employee salary\t: ";
    }

    comic = strtod(comic_string.c_str(), NULL);

        multiplePay = comic + multiplePay; // update previous salary with new user input
        cout << multiplePay;
    cout << "Add other pay?"; // add new salary again?
    int y;

    cin >> y;
    if (y == 1){


        cout << multiplePay;
    }
    else{
        break;
    }
    } // while

cout << multiplePay;  //the sum of all salary

Using cin.get() will solve the problem but the first user salary input will become 0 and only the next input will be calculated. Help me with this please. Thanks in advance.

Community
  • 1
  • 1
sg552
  • 1,521
  • 6
  • 32
  • 59

2 Answers2

3

Your problem is that cin >> y; will read an int, but leave the end-of-line \n in the input buffer. Next time you use getline, it will find this end-of-line immediately and not wait for any more input.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • Yes, that's the problem. Adding `cin.get()` in the final `if statement` solved the problem. Thanks again. – sg552 Dec 22 '12 at 10:20
1

std::basic_ios::eof() (in ss.eof()) doesn't work as you might think it works.

    if (ss >> comic_double)
    {
        if (ss.eof())
        {   // Success so get out
            break;
        }
    }

ss.eof() will only be true if a call of ss.get() or another extraction failed because you were at the end of the file. It doesn't matter whether the cursor is currently at the end.

Note that you fix this very easily by using ss.get():

    if (ss >> comic_double)
    {
        ss.get(); // if we are at the end ss.eof() will be true after this op

        if (ss.eof())
        {   // Success so get out
            break;
        }
    }
Zeta
  • 103,620
  • 13
  • 194
  • 236