Issue with string and spaces

I have the following code in my program and it is not working as intended.
1
2
3
4
5
6
7
8
9
string getName = ""; 
	double getWeight = 0; 
	int getHeight = 0; 
	double displayBmi; 
	
	
		//Get name
		cout << "Enter your name: ";
		cin >> getName;


What I intend it to do is be able to enter a name containing a space, such as "First name (space) Last name" and move on to the next part of the program.
The results I get are as follows:

Enter only one word/name with no spaces: Program functions perfectly
Enter name containing space: Program bypasses the following 2 questions and runs a formula based on erroneous values and gives me a bad result, then terminates.

I have also tried this with getline(cin, getName); on line 9 instead and receive the same results.
I have also tried this with getline(cin, getName); on line 9 instead and receive the same results.

No you didn't. You might have gotten an empty string depending on the contents of the input stream (that may have been left in the stream when a previous extraction took place,) but you didn't get the same results.

getline is the right tool to use here. If you have an issue with whitespace not being extracted from a previous extraction, remove it yourself:

std::getline((std::cin >> std::ws), getName);

Btw, you would not normally name a variable getXXX. Such names are generally used for functions which would actually do what the name suggests as opposed to variables which are incapable of doing what the name suggests.

Topic archived. No new replies allowed.