very basic C++ program closes after user input for no particular reason?

前端 未结 7 1185

I just started learning C++ and I wrote this sample program from the text and when I compile and run it, it just closes after the user inputs any number and presses enter.

相关标签:
7条回答
  • 2021-01-18 04:39

    The program closes because there's nothing more for the program to do. It outputs the final statements really really fast and then reaches return 0 which causes it to exit. You'll want to do something there to pause the program.

    On Windows, a basic way to do that is system("pause"); (you will need #include <stdlib.h>)

    cin.getline is a more standard way to do it.

    0 讨论(0)
  • 2021-01-18 04:39

    The program you posted has an error. I was not able to compile what you posted.

      cout << "Hello Reader.\n"
       << "Welcome to C++.\n"
    

    is not terminated with a semicolon. I added a semicolon and it compiles and runs as you expect.

    Edit: Of course, you have to run the program in a terminal that stays open after the program exits, or use cin to wait for more input, or something like that.

    0 讨论(0)
  • 2021-01-18 04:48

    Either put another read from cin to wait for the user, or open the Command Prompt yourself and run it there.

    0 讨论(0)
  • 2021-01-18 04:52

    Your program ends right after you print out your text. If you want to see anything on the screen you can add a cin right before your return 0 so your program waits for a user response before exiting.

    // Wait for user to hit enter
    cin >> dummyVar;
    
    return 0;
    
    0 讨论(0)
  • 2021-01-18 05:02

    It closes because the execution reaches return 0; and there is nothing left to do.

    If you want the program to wait before closing you could add an something like this:

    cout << "Press enter to exit...";
    cin  >> someVarThatWontBeUsed;
    

    You could also run the program from the command line instead of running the .exe. It will reach end of execution anyway but the prompt will stay open.

    0 讨论(0)
  • After the user inputs a number, which is saved to numberOfLanguages, it reaches return 0 which returns from the main function and thus the program ends.

    0 讨论(0)
提交回复
热议问题