system(“pause”); - Why is it wrong?

前端 未结 13 2083
轻奢々
轻奢々 2020-11-21 07:39

Here\'s a question that I don\'t quite understand:

The command, system(\"pause\"); is taught to new programmers as a way to pause a program and wait for

相关标签:
13条回答
  • 2020-11-21 08:03
    system("pause");  
    

    is wrong because it's part of Windows API and so it won't work in other operation systems.

    You should try to use just objects from C++ standard library. A better solution will be to write:

    cin.get();
    return 0;
    

    But it will also cause problems if you have other cins in your code. Because after each cin, you'll tap an Enter or \n which is a white space character. cin ignores this character and leaves it in the buffer zone but cin.get(), gets this remained character. So the control of the program reaches the line return 0 and the console gets closed before letting you see the results.
    To solve this, we write the code as follows:

    cin.ignore();  
    cin.get();  
    return 0;
    
    0 讨论(0)
提交回复
热议问题