Mosseman Mosseman - 10 months ago 45
C++ Question

Newbie struggles with std::cin

I'm having an issue where a simple function appears to terminate when it reaches an std::cin request. The compiler throws no warnings or errors and no run-time errors occur, the program simply falls back to main menu.


#include <iostream>
#include <math.h>

using namespace std;

void circle()
float radius = 0.0f, diameter = 0.0f, circumference = 0.0f, area = 0.0f;
const float pi = 3.14f;

cout << "Enter radius." << endl;
cin >> radius;
cout << "Radius: " << radius << endl;
cout << "Diameter: " << 2*radius << endl;
cout << "Cirumference: " << 2*pi*radius << endl;
cout << "Area: " << pi * pow(radius, 2) << endl;

The function is called from main() and is successfully called as "Enter radius" appears on the screen, but no input is requested and the last 4 statements are skipped. The program then simply returns to main().

cin is also error free (and continues to work while playing in the main() function) so I don't think it's simply reading a bad character in the stream.

I just can't figure out why circle() quits unexpectedly.


Well, it works fine on my computer. Did you debug it and does it really skips those lines? Add

cout << flush;

an the end to flush the buffer and see the results on the screen.

Remember to also clean the cin buffer before reading from it if you want it to block the executing program and wait for input from a user.