Mosseman
Mosseman

Reputation: 55

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.

Snippet:

#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.

Upvotes: 2

Views: 360

Answers (3)

Carl Winder
Carl Winder

Reputation: 948

It does the same on my machine when I try and run your code using Visual Studio 2010 on Windows XP.

I managed to fix it by putting getchar(); after the call to circle() in main.

Not sure why this is happening, hopefully someone can shed some more light on it.

**EDIT:

Of course it'll quit, it's because it'll run to the end of main which quits the app.

Upvotes: 2

SOReader
SOReader

Reputation: 6017

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.

Upvotes: 1

Walter
Walter

Reputation: 45434

cin doesn't request input, but just reads from stdin. So you program will print out

Enter radius.

followed by a new line. Then you can just type the radius and hit return. Did you try that?

Upvotes: 1

Related Questions