getline skips first ?

Hey, I'm wondering if someone can help me with my problem. In my code, getline skips the first time it's used. I have no idea how to get it working right, and no other solution I found fits. Any help would be appreciated. Also, the code I'm writing here is only a small piece of the program:

index = 0;
while (index < 10 && index != -999)
{
cout << "Please enter the name for trader number ";
cout << trader[index].traderNumber << endl;
getline(cin, trader[index].traderName);
index++;
}
Last edited on
This is the code I have now, including the above code with the same problem. This is NOT my final code so please ignore anything else you see. I still have the same problem.

The bold section is where I'm having problems. It's not allowing input for the first name, but instead going on to the second.



#include <iostream>
#include <iomanip>
#include <string>
using namespace std;


struct TraderInfo
{
int traderNumber;
string traderName;
double traderProfit;

};

int main()
{
TraderInfo trader[10];
int index = 0;

while (index < 10 && index != -999)
{
cout << "Please enter the trader number for trader ";
cout << index + 1;
cout << " ,or enter -999 if there are no more traders.\n";
cin >> trader[index].traderNumber;
index++;
}

int count = 0;
while (count < index && index != -999)
{
cout << "Please enter the name for trader number ";
cout << trader[count].traderNumber << endl;
getline(cin, trader[count].traderName);
count++;

}

index = 0;
while (index < 10)
{
cout << trader[index].traderNumber << endl;
cout << trader[index].traderName << endl;
index++;
}

system ("PAUSE");
return 0;
}


Last edited on
Before this code snip you have some code somewhere in your program where you are using something as

cin >> variable;

After entering variable and pressing ENTER key the new line character is still in the input buffer. So the next getline reads empty string until it meets this new line character.

try this statement before your code snip

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

You should include header <limits>
Last edited on
Thank you! That works. The only thing is, it does allow me to enter input for the first name, but it gives an extra space for each name after. So when I type the second name and press enter, it remains in that variable awaiting further input. If I press enter again it'll move on to the next. Is there any way to stop that, or is it stuck like that? And thanks again for the help.
You should place this statement I pointed out outside the loop.
Thank you again.
Last edited on
Topic archived. No new replies allowed.