C++ 中是否有像样的等待函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/902261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a decent wait function in C++?
提问by DeadHead
One of the first things I learned in C++ was that
我在 C++ 中学到的第一件事是
#include <iostream>
int main()
{
std::cout<<"Hello, World!\n";
return 0;
}
would simply appear and disappear extremely quickly without pause. To prevent this, I had to go to notepad, and save
会毫不停顿地极快地出现和消失。为了防止这种情况,我不得不去记事本,并保存
helloworld.exe
pause
ase
酶
helloworld.bat
This got tedious when I needed to create a bunch of small test programs, and eventually I simply put while(true);
at the end on most of my test programs, just so I could see the results. Is there a better wait function I can use?
当我需要创建一堆小型测试程序时,这变得很乏味,最终我只是将while(true);
大多数测试程序放在最后,以便我可以看到结果。我可以使用更好的等待功能吗?
回答by DeadHead
you can require the user to hit enter before closing the program... something like this works.
您可以要求用户在关闭程序之前按 Enter 键……类似这样的操作。
#include <iostream>
int main()
{
std::cout << "Hello, World\n";
std::cin.ignore();
return 0;
}
The cin reads in user input, and the .ignore() function of cin tells the program to just ignore the input. The program will continue once the user hits enter.
cin 读入用户输入,cin 的 .ignore() 函数告诉程序忽略输入。一旦用户点击进入,程序将继续。
回答by borderless
Please note that the code above was tested on Code::Blocks 12.11 and Visual Studio 2012
on Windows 7.
请注意,上面的代码
在 Windows 7上的 Code::Blocks 12.11 和 Visual Studio 2012上进行了测试。
For forcing your programme stop or wait, you have several options :
要强制您的程序停止或等待,您有几种选择:
- sleep(unsigned int)
- 睡眠(无符号整数)
The value has to be a positive integer in millisecond. That means that if you want your programme wait for 2 seconds, enter 2000.
该值必须是以毫秒为单位的正整数。这意味着如果您希望程序等待 2 秒,请输入 2000。
Here's an example :
这是一个例子:
#include <iostream> //for using cout
#include <stdlib.h> //for using the function sleep
using namespace std; //for using cout
int main(void)
{
cout << "test" << endl;
sleep(5000); //make the programme waiting for 5 seconds
cout << "test" << endl;
sleep(2000); // wait for 2 seconds before closing
return 0;
}
If you wait too long, that probably means the parameter is in seconds. So change it to this:
如果等待时间过长,则可能意味着参数以秒为单位。所以把它改成这样:
sleep(5);
For those who get error message or problem using sleep try to replace it by _sleep or Sleep especially on Code::Bloks.
And if you still getting problems, try to add of one this library on the beginning of the code.
对于那些在使用 sleep 时收到错误消息或问题的人,请尝试将其替换为 _sleep 或 Sleep,尤其是在 Code::Bloks 上。
如果您仍然遇到问题,请尝试在代码的开头添加一个此库。
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <dos.h>
#include <windows.h>
- system("PAUSE")
- 系统(“暂停”)
A simple "Hello world" programme on windows console application would probably close before you can see anything. That the case where you can use system("Pause").
Windows 控制台应用程序上的一个简单的“Hello world”程序可能会在您看到任何内容之前关闭。那就是您可以使用 system("Pause") 的情况。
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
system("PAUSE");
return 0;
}
If you get the message "error: 'system' was not declared in this scope" just add the following line at the biggining of the code :
如果您收到消息“错误:'系统'未在此范围内声明”,只需在代码的大写处添加以下行:
#include <cstdlib>
- cin.ignore()
- cin.ignore()
The same result can be reached by using cin.ignore() :
使用 cin.ignore() 可以达到相同的结果:
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.ignore();
return 0;
}
- cin.get()
- cin.get()
example :
例子 :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.get();
return 0;
}
- getch()
- 获取()
Just don't forget to add the library conio.h :
只是不要忘记添加库 conio.h :
#include <iostream>
#include <conio.h> //for using the function getch()
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
getch();
return 0;
}
You can have message telling you to use _getch() insted of getch
你可以有消息告诉你使用 _getch() insted of getch
回答by Lightness Races in Orbit
Lots of people have suggested POSIX sleep
, Windows Sleep
, Windows system("pause")
, C++ cin.get()
… there's even a DOS getch()
in there, from roughly the late 1920s.
很多人建议使用 POSIX sleep
、 Windows Sleep
、 Windows system("pause")
、 C++ cin.get()
……那里甚至还有 DOS getch()
,大约从 1920 年代后期开始。
Pleasedon't do any of these.
请不要做这些。
None of these solutions would pass code review in my team. That means, if you submitted this code for inclusion in our products, your commit would be blocked and you would be told to go and find another solution. (One might argue that things aren't so serious when you're just a hobbyist playing around, but I propose that developing good habits in your pet projects is what will make you a valued professional in a business organisation, and keep you hired.)
这些解决方案都不能通过我团队的代码。这意味着,如果您提交此代码以包含在我们的产品中,您的提交将被阻止,您将被告知去寻找另一个解决方案。(有人可能会争辩说,当你只是一个业余爱好者时,事情并没有那么严重,但我建议在你喜欢的项目中养成良好的习惯将使你成为商业组织中有价值的专业人士,并让你继续被雇佣。 )
Keeping the console window open so you can read the output of your program is notthe responsibility of your program! When you add a wait/sleep/block to the end of your program, you are violating the single responsibility principle, creating a massive abstraction leak, and obliterating the re-usability/chainability of your program. It no longer takes input and gives output — it blocks for transient usage reasons. This is very non-good.
保持控制台窗口打开以便您可以阅读程序的输出不是您的程序的责任!当您在程序末尾添加等待/睡眠/块时,您违反了单一职责原则,造成了大量抽象泄漏,并消除了程序的可重用性/可链接性。它不再接受输入并提供输出——它会因为暂时使用的原因而阻塞。这是非常不好的。
Instead, you should configure your environmentto keep the prompt open after your program has finished its work. Your Batch script wrapper is a good approach!I can see how it would be annoying to have to keep manually updating, and you can't invoke it from your IDE. You could make the script take the path to the program to execute as a parameter, and configure your IDE to invoke it instead of your program directly.
相反,您应该配置您的环境以在您的程序完成其工作后保持提示打开。您的批处理脚本包装器是一个好方法!我可以看到必须不断手动更新会很烦人,而且您无法从 IDE 中调用它。您可以让脚本将要执行的程序路径作为参数,并将您的 IDE 配置为调用它而不是直接调用您的程序。
An interim, quick-start approach would be to change your IDE's run commandfrom cmd.exe <myprogram>
or <myprogram>
, to cmd.exe /K <myprogram>
. The /K
switch to cmd.exe
makes the prompt stay open after the program at the given path has terminated. This is going to be slightly more annoying than your Batch script solution, because now you have to type exit
or click on the red 'X' when you're done reading your program's output, rather than just smacking the space bar.
一种临时的快速启动方法是将IDE 的运行命令从cmd.exe <myprogram>
或更改<myprogram>
为cmd.exe /K <myprogram>
。该/K
开关cmd.exe
品牌在给定的路径程序后提示保持打开状态已经终止。这将比您的批处理脚本解决方案更烦人,因为现在exit
您在阅读完程序的输出后必须键入或单击红色的“X”,而不仅仅是敲击空格键。
I assume usage of an IDE, because otherwise you're already invoking from a command prompt, and this would not be a problem in the first place. Furthermore, I assume the use of Windows (based on detail given in the question), but this answer applies to any platform… which is, incidentally, half the point.
我假设使用 IDE,因为否则您已经从命令提示符调用了,这首先不是问题。此外,我假设使用 Windows(基于问题中给出的详细信息),但此答案适用于任何平台……顺便说一句,这是重点的一半。
回答by dmckee --- ex-moderator kitten
The appearance and disappearance of a window for displaying text is a feature of how you are running the program, not of C++.
用于显示文本的窗口的出现和消失是程序运行方式的一个特性,而不是 C++ 的特性。
Run in a persistent command line environment, or include windowing support inyour program, or use sleep
or wait on input as shown in other answers.
在持久的命令行环境中运行,或在程序中包含窗口支持,或者使用sleep
或等待输入,如其他答案中所示。
回答by SingleNegationElimination
the equivalent to the batch program would be
相当于批处理程序是
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
std::cin.get();
return 0;
}
The additional line does exactly what PAUSE
does, waits for a single character input
附加行的作用正是PAUSE
如此,等待单个字符输入
回答by Kevin
There is a C++11 way of doing it. It is quite simple, and I believe it is portable. Of course, as Lightness Races in Orbitpointed out, you should not do this in order to be able to see an Hello Worldin your terminal, but there exist some good reason to use a wait function. Without further ado,
有一种 C++11 的方式来做到这一点。它非常简单,我相信它是便携的。当然,正如Orbit 中的 Lightness Races指出的那样,您不应该为了能够在终端中看到Hello World而这样做,但是使用等待功能是有充分理由的。无需再费周折,
#include <chrono> // std::chrono::microseconds
#include <thread> // std::this_thread::sleep_for
std::this_thread::sleep_for(std::chrono::microseconds{});
More details are available here. See also sleep_until.
可在此处获得更多详细信息。另见sleep_until。
回答by rr-
Actually, contrary to the other answers, I believe that OP's solution is the one that is most elegant.
实际上,与其他答案相反,我认为 OP 的解决方案是最优雅的解决方案。
Here's what you gain by using an external .bat
wrapper:
以下是使用外部.bat
包装器的好处:
- The application obviously waits for user input, so it already does what you want.
- You don't clutter the code with awkward calls. Who should wait?
main()
? - You don't need to deal with cross platform issues - see how many people suggested
system("pause")
here. - Without this, to test your executable in automatic way in black box testing model, you need to simulate the
enter
keypress (unless you do things mentioned in the footnote). - Perhaps most importantly - should any user want to run your application through terminal (
cmd.exe
on Windows platform), they don'twant to wait, since they'll see the output anyway. With the.bat
wrapper technique, they can decide whether to run the.bat
(or.sh
) wrapper, or run the executable directly.
- 该应用程序显然在等待用户输入,因此它已经完成了您想要的操作。
- 你不会用笨拙的调用来弄乱代码。谁该等?
main()
? - 您不需要处理跨平台问题 - 看看
system("pause")
这里有多少人建议。 - 如果没有这个,要在黑盒测试模型中以自动方式测试您的可执行文件,您需要模拟
enter
按键(除非您执行脚注中提到的操作)。 - 也许最重要的是-如果任何用户想要通过终端(可以运行应用程序
cmd.exe
在Windows平台上),他们不希望等待,因为他们会看到反正输出。使用.bat
包装器技术,他们可以决定是运行.bat
(或.sh
)包装器,还是直接运行可执行文件。
Focusing on the last two points - with any other technique, I'd expect the program to offer at least --no-wait
switch so that I, as the user, can use the application with all sort of operations such as piping the output, chaining it with other programs etc. These are part of normal CLI workflow, and adding waiting at the end when you're already inside a terminal just gets in the way and destroys user experience.
关注最后两点 - 使用任何其他技术,我希望该程序至少提供--no-wait
开关,以便我作为用户可以使用该应用程序进行各种操作,例如管道输出,将其与其他程序等。这些是正常 CLI 工作流程的一部分,当您已经在终端内时,在最后添加等待只会妨碍并破坏用户体验。
For these reasons, IMO .bat
solution is the nicest here.
由于这些原因,IMO.bat
解决方案在这里是最好的。
回答by poliklosio
What you have can be written easier. Instead of:
你拥有的东西可以更容易地写出来。代替:
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
return 0;
}
write
写
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
system("PAUSE");
return 0;
}
The system function executes anything you give it as if it was written in the command prompt. It suspends execution of your program while the command is executing so you can do anything with it, you can even compile programs from your cpp program.
system 函数执行你给它的任何东西,就好像它写在命令提示符中一样。它在命令执行时暂停程序的执行,因此您可以使用它做任何事情,您甚至可以从您的 cpp 程序编译程序。
回答by Ivan Prodanov
Syntax:
句法:
void sleep(unsigned seconds);
无效睡眠(无符号秒);
sleep() suspends execution for an interval (seconds). With a call to sleep, the current program is suspended from execution for the number of seconds specified by the argument seconds. The interval is accurate only to the nearest hundredth of a second or to the accuracy of the operating system clock, whichever is less accurate.
sleep() 暂停执行一段时间(秒)。调用 sleep 时,当前程序将暂停执行参数 seconds 指定的秒数。间隔仅精确到最接近的百分之一秒或操作系统时钟的精确度,以较不精确的为准。
This example should make it clear:
这个例子应该清楚:
#include <dos.h>
#include <stdio.h>
#include <conio.h>
int main()
{
printf("Message 1\n");
sleep(2); //Parameter in sleep is in seconds
printf("Message 2 a two seconds after Message 1");
return 0;
}
Remember you have to #include dos.h
记住你必须#include dos.h
EDIT:
编辑:
You could also use winAPI.
您也可以使用 winAPI。
VOID WINAPI Sleep(
DWORD dwMilliseconds
);
Just a note,the parameter in the function provided by winapi is in milliseconds ,so the sleep line at the code snippet above would look like this "Sleep(2000);"
请注意,winapi 提供的函数中的参数以毫秒为单位,因此上面代码片段中的 sleep 行看起来像这样“Sleep(2000);”
回答by Eric Bainville
getchar() provides a simplistic answer (waits for keyboard input). Call Sleep(milliseconds) to sleep before exit. Sleep function (MSDN)
getchar() 提供了一个简单的答案(等待键盘输入)。在退出前调用 Sleep(milliseconds) 休眠。 睡眠功能(MSDN)