Decimal / Enter key problem

As seen in my code below I have 'double' to allow for decimals. Below 'cin >> length;' I have the 'cin.ignore();' which should ignore the enter. So, it shouldn't be skipping the 'Enter the width of the rectangle:' It's skipping the line anyway. I emailed my professor but this is our first assignment and he gave me a hint. It was completely useless considering I've never coded in the language. Any suggestions? Thanks

Code:
// This Program lets the user find the area of a triangle
// Name: Annie Walinder

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
string name;
double length, width;

cout << "Please enter your full name: ";
getline(cin, name);
cin.ignore();

cout << "Enter length of the rectangle: ";
cin.ignore();
cin >> length;

cout << "Enter width of the rectangle: ";
cin >> width;

cout << "Hello, " << name << endl;
cout << "With the length of " << length << " and the width of " << width << " you have entered, the area is " << (width * length) << endl;

return 0;
}

remove all the ignores. you don't need them here.

This is way oversimplified: you should re-read a good web page on the topic of ignore with respect to getline and cin statements. But it will get you working right away if the user enters reasonable values (they can still break it, and you can inject more ignores and code to deal with that, but lets start slow).
Last edited on
Put simply, >> ignores leading white-space (space, tab, \n) and stops extraction when an invalid char is read (eg z for a number) or a white-space char is found. The char causing >> to stop is not removed.

getline() extracts all chars up to and including the terminating char (\n by default). The terminating char is then ignored. It does not ignore leading white-space.

The issue becomes when you have >> followed by getline(). The >> leaves the terminating \n which is then obtained by the getline(), ignored and the getline() returns with an empty string. The .ignore() before a getline() is to remove the \n left by the >> . Multiple >> are OK as >> ignores the leading \n left by the previous \n which getline() doesn't.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string name;
	double length {}, width {};

	cout << "Please enter your full name: ";
	getline(cin, name);

	cout << "Enter length of the rectangle: ";
	cin >> length;

	cout << "Enter width of the rectangle: ";
	cin >> width;

	cout << "Hello, " << name << '\n';
	cout << "With the length of " << length << " and the width of " << width << " you have entered, the area is " << (width * length) << '\n';

	return 0;
}

Last edited on
Topic archived. No new replies allowed.