seems to be skipping inputs...

Hello. I've been learning C++ from a few tutorials for 2 weeks now and I've recently written a small program. I wrote a very similar program a few days ago and had no problems, but now when I attempt to recreate it I get some problems. First, here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# include <iostream>
# include <string>
# include <sstream>
# include <fstream>

using namespace std;

struct check {
string item;
int condition;
}bestbuy [50];

void qualitycheck (check condition)
{
    cout<<"Item: ("<<condition.item<<") ";
    if (condition.condition > 50)
    {
        cout<<"has passed inspection.";
    }
    else if (condition.condition < 50)
    {
        cout<<"has failed inspection"<<endl;
        cout<<"------------------------------------";
    }
}

int main ()
{
    int a;
    int b;
    string mystr;

    cout<<"How many items are you checking in?: ";
    cin>>a;

    for (b=0;b<a;b++)
    {
        cout<<"Please enter the name of the item: ";
        getline (cin,bestbuy[b].item);


        cout<<"Please enter the condition of the item (0-100): ";
        cin>>mystr;
        stringstream (mystr) >> bestbuy[b].condition;
    }
    for (b=0;b<a;b++)
    {
        qualitycheck (bestbuy[b]);
    }
    return 0;
}


Anyways, the problem I'm having is that the program, for whatever reason, goes through:
1
2
3
4
5
6
cout<<"Please enter the name of the item: ";
        getline (cin,bestbuy[b].item);


        cout<<"Please enter the condition of the item (0-100): ";
        cin>>mystr;

Without stopping at getline for input. It readsout "Please enter the name of the item: Please enter the condition of the item (0-100):. And then I may enter only 1 input which I assume is for the cin>>mystr.

Its really annoying that I got this to work a few days ago but now I just can't figure out what would make it skip the first input.
If you compile the code it should show my problem in detail. Any suggestions?
thanks.
This is because when you ask for a number (int) the user types in a line, but the program only reads in the number, leaving the end of the line for the next instruction to read. So your getline() function reads the end of line from when you typed in the number.

You can do this to skip over the end of line:
1
2
3
4
5
6
7
#include <iomanip>

// ...

int a;

std::cin >> a >> std::ws; // after reading in the number, skip over any white-space (takes you to next line) 
*edit. I got it to work perfectly by simply getting rid of any instance of cin>> by using getlines only.
I don't quite understand your explaination though, could you try rewording it, please?
Last edited on
Topic archived. No new replies allowed.