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

Started by
0 comments, last by Zahlman 17 years, 4 months ago
***************************************************** #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.
Advertisement
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)

This topic is closed to new replies.

Advertisement