Pointer/Structure skips input

The program skips the "Enter the pizza's weight: " part, if the string for "Enter the pizza company name: " has a whitespace.

The program's output:
Enter the pizza's diameter: 3
Enter the pizza company name: dumb pizza
Enter the weight of the pizza: Name: dumb
Weight: -4.31602e+008
Diameter: 3
Press any key to continue . . .


edit: Now I can't compile the program. The following error appears:

Unhandled exception at 0x1029e9ee in source.exe: 0xC0000005: Access violation reading location 0x206b6f6f.


The source 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
#include <iostream>
#include <string>
using namespace std;

struct pizza
{
	std::string name;
	float diameter;
	float weight;
};

int main()
{
	pizza * pointer = new pizza;
	cout << "Enter the pizza's diameter: ";
	cin >> (*pointer).diameter;
	cout << "Enter the pizza company name: ";
	cin >> pointer->name;
	cout << "Enter the weight of the pizza: ";
	cin >> (*pointer).weight;
	cout << "Name: " << pointer->name << endl;
	cout << "Weight: " << pointer->weight << endl;
	cout << "Diameter: " << pointer->diameter << endl;
	delete [] pointer;
	system("pause");
	return 0;
}
Last edited on
delete [] pointer You didn't allocate an array. It should look like delete pointer;

1
2
delete pointer;       // Delete memory allocated for a single element
delete [] pointer;    // Delete memory allocated for arrays of elements 


Last edited on
Oh right.

But why does it skip the "Enter the pizza's weight: " part, due to the whitespace in the string.
Hence the program works fine if you type in a string without spaces in it.
It is skipping because it is reading whatever is after the space as input for the next question. So if you have your program print out the variable for the pizza's weight, you should get the second word/string of the input. But I forget how to fix it!

I think this might help you out!

http://www.cplusplus.com/reference/iostream/istream/getline/
Last edited on
Problem solved:

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
#include <iostream>
#include <string>
using namespace std;

struct pizza
{
	std::string name;
	float diameter;
	float weight;
};

int main()
{
	pizza * pointer = new pizza;
	cout << "Enter the pizza's diameter: ";
	(cin >> (*pointer).diameter).get(); // embrace statement with brackets and add .get()
	cout << "Enter the pizza company name: ";
	getline(cin, pointer->name); // for string input
	cout << "Enter the weight of the pizza: ";
	(cin >> (*pointer).weight).get(); // embrace statement with brackets and add .get()
	cout << "Name: " << pointer->name << endl;
	cout << "Weight: " << pointer->weight << endl;
	cout << "Diameter: " << pointer->diameter << endl;
	delete pointer;
	system("pause");
	return 0;
}


Thanks guys!
Topic archived. No new replies allowed.