Question about strings

Ok when I run this it seems to work fine till the input loop goes and repeats. It then skips over asking for the name of the company and goes straight to weight. I've tried the different ways of getting input (at least ones that are at my skill level as of right now). The best solution I've found was to use the following.

getline(cin, pizza[i].pizzaCompany, '\n');

I'm currently using the c++ primer 3rd edition and in the chapter that introduces strings it also introduces pointers. I understand pointers at least in plain english but have yet to understand the syntax. So how do I get this to work? And whats the best way to implement pointers in this example? Such as can I use pointer arithmetic to go through the array instead of using a for loop.

Thanks for all the 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
36
37
38
#include<iostream>
#include<string>
using namespace std;

struct foodStruct
{
	string pizzaCompany;
	int pizzaWeight;
	int pizzaSize;
};

const int ArrSize = 3;

int main()
{
	foodStruct pizza[ArrSize];
	
	for (int i = 0; i < ArrSize; i++)
	{
		cout << "Name of Company: ";
		getline(cin, pizza[i].pizzaCompany, '\n'); // questionable code?
		cout << "Pizza Weight (in lbs): ";
		cin >> pizza[i].pizzaWeight;
		cout << "Pizza Size (in inches): ";
		cin >> pizza[i].pizzaSize;
	}

	for (int i = 0; i < ArrSize; i++)
	{
		cout << "Pizza Comapny :" << endl;
		cout << pizza[i].company << endl;
		cout << "Pizza Weight :" << endl;
		cout << pizza[i].pizzaWeight << " lb(s)" << endl;
		cout << "Pizza Size :" << endl;
		cout << pizza[i].pizzaSize << " inche(s)" << endl;
	}
	return 0;
}

Last edited on
Don't mix cin >> x with getline( cin, s ).
http://www.cplusplus.com/forum/articles/6046/

The questionable code is on lines 23 and 25.
1
2
3
4
#include <iostream>
#include <limits>
#include <string>
using namespace std;
1
2
3
4
5
6
7
8
9
10
11
12
13
	for (int i = 0; i < ArrSize; i++)
	{
		cout << "Name of Company: ";
		getline(cin, pizza[i].pizzaCompany, '\n');

		cout << "Pizza Weight (in lbs): ";
		cin >> pizza[i].pizzaWeight;
		cin.ignore(numeric_limits<streamsize>::max(), '\n');

		cout << "Pizza Size (in inches): ";
		cin >> pizza[i].pizzaSize;
		cin.ignore(numeric_limits<streamsize>::max(), '\n');
	}

Enjoy!
Topic archived. No new replies allowed.