Problem reading strings

I'm writing a program that reads a users name and stores it in a dynamically allocated array, however when reading the name, it works fine if it's a single word, but if you put a space in it, it won't work. Why?

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
 // Chapter 6 exercise 6
#include <iostream>
#include <string>

struct contribs
{
	std::string name;
	double donation;
};

int main()
{
	using namespace std;
	int contributors;

	cout << "Enter the number of contributors: ";
	cin >> contributors;

	contribs *donors = new contribs[contributors];

	for (int i = 0; i < contributors; i++)
	{
		cout << "Please enter contributors name: ";
		cin >> donors[i].name;
		cout << "Enter contributors donation amount: $";
		cin >> donors[i].donation;
	}
	delete [] donors;
	return 0;
}


It won't ask for the rest of the names or contributions if the name has a space in it.
closed account (j3Rz8vqX)
cin is delimited by space and newline.

An alternative would be getline(ARG1,ARG2). which is delimited by newline.
getline(cin,donors[i].name);

There are two getline functions:

The iostream version:
http://www.cplusplus.com/reference/istream/istream/getline/

The string version:
http://www.cplusplus.com/reference/string/string/getline/
I'm not 100%, but maybe you could replace the cin at line 24 with:
getline( std::cin, doners[i].name );
Topic archived. No new replies allowed.