how to display char arrays

closed account (EAXiz8AR)
How do you display char arrays that are two or more words?

For example, I'm making this simple program where I have declared

1
2
3
4
5
char country[50];
cout << "Please enter your country of origin";
cin >> country;

cout << country;


But when I type in, for example, "United States" and store it in the array "country", the computer outputs only "United". Can you guys help me fix this?

thanks
The problem is cin. It takes the input until the first space, but returns on enter.

Use getline instead:

There're two versions.

This takes an array:
http://www.cplusplus.com/reference/iostream/istream/getline/

This takes a string:
http://www.cplusplus.com/reference/string/getline/
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <sstream>
using namespace std;

int main() {
	char country[50];
	cout << "Enter your country of origin: ";
	cin.getline(country, 50);
	cout << country << endl;
}


Or

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <sstream>
using namespace std;

int main() {
	string country;
	cout << "Enter your country of origin: ";
	getline(cin, country);
	cout << country << endl;
}



Second one would be recommended because strings are generally easier to deal with than character arrays.
Topic archived. No new replies allowed.