简体   繁体   中英

Console Application doesn't function correctly outside of Visual Studio

I recently picked up C++ Primer Fifth Edition and have very limited knowledge of c++ or Visual Studio. Using Visual Studio 2017 Community, I composed the simple "Enter two numbers" program with the code shown below.

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

int main()
{
    std::cout << "Enter two numbers:" << std::endl;
    int v1 = 0, v2 = 0;
    std::cin >> v1 >> v2;
    std::cout << "The sum of " << v1 << " and " << v2 << " is " 
        << v1 + v2 << std::endl;
    return 0;
}

When I run this program within Visual Studio it functions correctly (start with and without debugging) by waiting for my input and then returning the sum of the two integers. However, when I navigate to the executable file in File Explorer and run it, it immediately closes after I type the two integers and press enter. I also watched closely to make sure that the sum wasn't returned before the application closed. I'm sure it's a simple fix given that I'm a beginner, but I can't seem to find a suitable solution online. Anyone know why this might be?

Open a console window, and run it from the command prompt. Or prompt for input before you end your program.

When you double click a program in File Explorer, Windows will create a console for it if necessary. When the program terminates, that console window will close. Since your program prints the result then immediately exits, you don't have time to see the result before the window closes.

After displaying the result, your program is finished, so its window gets right away closed. Therefore, you never see the result (it is probably 'visible' for less than one frame).

If you run it in Visual Studio, the environment provides you a permanent window, so you can see the result.

Try to open a CMD window, and execute the file in there (drag it with the mouse, or type its path and name). You will then see the results in that window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM