简体   繁体   中英

c++ getchar works in vs 2010, doesn't in 2012

Why the program just exits, in vs 2012, while in 2010 does it wait for my input?

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

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string path = "c:\somepath";
    cout << "Path is" + path << endl;
    getchar();
    return 0;
}

The getchar() function is not used in the program flow and only the side effect of waiting for input is used in your case. Instead of hacking your program to avoid closing the window you should use the proper way to keep it open.

Choose one of:

  1. Command window

    • open a command prompt
    • navigate to the folder where you want your program to execute
    • type the path to the .exe and hit Enter. The command prompt is still open after execition of your program and there is not need for getchar() .
  2. Start without debugging

    • just use the menu item Debug->Start Without Debugging. The new console window is still open after execition of your program and there is not need for getchar() .
  3. Start with debugging

    • Set a breakpoint at the closing '}' of your main function.
    • use the menu item Debug->Start. The debugging session is still active and the window for your console program is still open. There is not need for getchar() .

Why you should avoid getchar() to keep a window open?

  • It's a hack that depends on the program before. There can be some characters in the input buffer as pointer out here: getchar() doesn't work well?

  • Your program can't be used in batch file if you come beyond the phase where you try to learn C or C++.

  • It's not necessary.

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