Sign in to follow this  
raghav

Abrupt termination in using std::cin (DevCPP compiler)

Recommended Posts

raghav    122
***************************************************** #include <iostream> #include <string> using namespace std; int main() { // ask for the person's name std::cout << "Please enter your first name:\n"; // read the name std::string name; // define name std::cin >> name; // read into // write a greeting std::cout << "Hello, " << name << "!" << std::endl; cin.get(); return 0; } ***************************************************** I am using std::cin to read the user input. The program prompts for the name. But then, when I enter the name, program terminates abruptly. Any idea why this is happening? Thanks.

Share this post


Link to post
Share on other sites
Zahlman    1682
Simple: your program reaches the end of execution. ('cin.get()' picks up the return character from the input. But even then, you'd have to allow for the possibility that the input contained more than one word...)

Moral: Don't try to pause your programs at the end artificially. Instead, accept that they end at a particular time, and run them in a proper way, such that you can see the last output. This can mean setting a breakpoint on the last line and selecting 'run without debugging' in your IDE; it can mean starting the program from the command line, or it can mean creating a batch file that runs your program and then the 'pause' program (do NOT run 'pause' from within your program).

Not only is this For Beginners material, BTW, but I'm seriously wondering why it isn't in the FAQ yet. (Or maybe it is, for all I know. Doesn't anyone ever read those things :( I don't because I don't have any beginner questions ;) but maybe I should check it anyway)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this