Help with std::getline.

I've tried running this program but it will not work.

Without the dummy variable, it just skips that line. Any help?

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
#include "stdafx.h"
#include <iomanip> 
#include <iostream> 
#include <fstream>
#include <assert.h>
#include <string>
#include <cstdlib> 
using namespace std; 

int _tmain(int argc, _TCHAR* argv[])
{
	int part_number[10], x, dummy;
	string description[10];
	double price[10];
	cout << "PART ARRAY SORTER" << endl;
	cout << "-----------------" << endl << endl;
	for(x = 0; x <= 9; x++)
	{
		cout << "Enter part number " << x + 1 << ": ";
		cin >> part_number[x];
		std::getline (std::cin, dummy);
		cout << "Emter the description of the item: " << endl;
		std::getline (std::cin, description[x]);
		cout << "Enter the price for the part: " << endl;
		cin >> price[x];
	}
	cout << endl << endl;
	cout << "---------------------------------------------------------" << endl;
	cout << "Part Number:       Description:                    Price:" << endl;
	for(x = 0; x <= 9; x++)
	{
		cout << setw(0) << part_number[x] << setw(19) << description[x] << setw(27) << price[x] << endl;
	}
	return 0;
}
remove the cin >> part_number[x]; and just do std::getline to get the input and then convert it from string to int and add it to your array
Instead of std::getline in line 21, use:
input.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

When you read in the int in line 20, the new line (from the enter key) is left in the stream. Ignore says ignore characters until I see a new line ('\n').

The ...max() means ignore all characters before the new line. If you enter an int, 56 spaces and then hit enter, there would be 56 spaces and a new line left in the stream. You want to make sure that all characters up through the new line are ignored.
Topic archived. No new replies allowed.