system(“pause”) clarification

假如想象 提交于 2020-01-06 03:36:13

问题


When i use system("pause"), then a line "Press any key to continue..." shows up on the screen.

This is iritating and makes reading the output quite cumbersome.

Is there some way to stop this from coming?


回答1:


Do you mean that you want to press any key to continue but not to display the "Press any key to continue" on the screen? Try this getchar(); this will capture one character typing from keyboard and continue.




回答2:


Rather than using platform dependent system("pause") you can use the platform independent std::cin.get() and if the buffer is messing with it, you can use:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n')

before hand to clear the buffer.




回答3:


Assuming you're on Windows, replace the system("pause") with system("pause > NULL").




回答4:


First of all, you should never use system("pause") because it is dangerous. Your code will be calling an external system procedure for no reason; and a cracker can find a way to substitute the "pause" command to other, making your program call the other program with your user permissions.

That said, you can avoid the message sending it to null device.

  • On Windows:

    pause > nul

And if you want to be bold to make this awful system call portable, you can use:

  • on linux:

    echo Press any key to continue ...; read x

Now you can apply the OR and AND (logic connectives) to both and make a system call that works on both systems:

void pause(void)
{
    system("echo Press any key to continue . . . && ( read x 2> nul; rm nul || pause > nul )");
    return;
}

Linux will create a temporary file called "nul" because it does not recognize this keyword. The null device on linux is /dev/null, not just nul. After that, the command will remove this temporary file with rm nul. So if you happen to have a file named nul on the same directory, be warned this command is not good for you (for yet another reason).

This command mimics the original. If you want to avoid the message, just remove the echo Pres... part of it.


Bonus:

  • Clear the terminal screen portably using system? (No, do not do this for the same reasons. Its dangerous.) But for tests purposes, you can use:

system("cls||clear");


Avoid pause. C is a language, one of the most powerful languages that there is. I'm sure there is a way to make a pause using only C (getchar() or scanf() for instance).




回答5:


That line is part of the system("pause"). You can try a different method, such as getline(std::cin, variable) or cin.get().




回答6:


Use

system("pause>nul")

It works perfectly for windows!



来源:https://stackoverflow.com/questions/15039322/systempause-clarification

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!