Need help with output (cout)

I have a program that has to calculate the area of a rectangle or a circle. It works well but it does not print me the output as I want it.

If I input this for example:
2
rectangle 10 2.5
circle 100

My program outputs this (showing input with {} so you can see undesired output location:
{2
rectangle 10 2.5
circle 100}25.000000

31415.926536


First of all, why does it cout the area of the first case (rectangle) after inputting the second case? Basically, I am meaning this "circle 10025.000000"

Why do I have to press enter after entering the input to get the SECOND AREA while the FIRST AREA it is calculated and printed after I copy paste the input?

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

int main() {
	cout.setf(ios::fixed);
	cout.precision(6);

	int n;
	double l,w,r,pi;
	pi = M_PI;
	string s;
	cin >> n;

	while (n != 0) {
		n--;		
		cin >> s;
		if (s == "rectangle") {
			cin >> l >> w;
			cout << l*w << endl;
		}
		if (s == "circle") {
			cin >> r;
			cout << pi*(r*r) << endl;
		}
	}
}
closed account (49iURXSz)
Your code works fine for me. Note I used the g++ compiler:

[StudentOfJack@testing02 fun]$ g++ --version
g++ (GCC) 6.2.1 20160916 (Red Hat 6.2.1-2)
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[StudentOfJack@testing02 fun]$ g++ -o cout-formatting.exe cout-formatting.cpp
[StudentOfJack@testing02 fun]$ ./cout-formatting.exe
2
rectangle 10 2.5
25.000000
circle 100
31415.926536
[StudentOfJack@testing02 fun]$


There may be some differences though with how the <istream> and <ostream> libraries are implemented on your platform. Do you know what IDE or compiler you're using?

Or, did you change your code since your post?
Last edited on
line 18
Topic archived. No new replies allowed.