简体   繁体   English

使用cmd运行C ++程序

[英]Running a C++ program with cmd

When I run a program through command line, once the program ends, cmd instantly closes, so I can't see the output easily. 当我通过命令行运行程序时,一旦程序结束,cmd将立即关闭,因此我无法轻松看到输出。 Is there anyway to stop this from happening so I can actually verify the output? 无论如何,有什么方法可以阻止这种情况的发生,以便我可以实际验证输出?

#include<iostream>
using namespace std;
class Exercises {
public: 
    void sayHello(int x) {
        for (int i = 0; i < x; i++)
            cout << "Hello!!" << endl;
    }
}exercise;

int main() {
    exercise.sayHello(4);
    return 0;
}

You can also use cin.get(); 您也可以使用cin.get();。

It will wait for you to press enter or until you close the program. 它将等待您按Enter或直到关闭程序。

Following methods can help in keeping the command window till another input is provided. 以下方法可以帮助保持命令窗口,直到提供另一个输入为止。

#include <conio.h>
void main(){

// your program here

 getch();
}

Another way is to use system("pause"); 另一种方法是使用system("pause"); at the end of your program. 在程序结束时。

You can pause the execution of the program for a certain amount of time with: 您可以使用以下方法将程序的执行暂停一定时间:

sleep(5); // sleep for 5 seconds

You could place that at the end of the program before return 0; 您可以在return 0;之前将其放在程序的末尾;否则, return 0; .

If you don't mind waiting for a keypress at the end of your program, you could put something in. 如果您不介意在程序结束时等待按键,则可以放入一些东西。

The simplest way in Windows is to do: Windows中最简单的方法是:

system("pause");

Don't do this if you are releasing your software though. 但是,如果要发布软件,则不要这样做。 You can implement the behaviour of the pause command easily enough. 您可以足够容易地实现pause命令的行为。

std::cout << "Press any key to continue . . . " << std::flush;
while( !_kbhit() ) Sleep(25);
getch();

That's using stuff from conio.h . 那是使用conio.h的东西。

However, I'm concerned about the cmd shell itself closing. 但是,我担心cmd shell本身会关闭。 When you say you "run with cmd", are you actually running up a shell, then typing in your program name and hitting Enter? 当您说“使用cmd运行”时,您实际上是在运行Shell,然后输入程序名称并按Enter吗? If that closes the shell, then something is wrong. 如果那关闭了外壳,则出了点问题。 More likely, you're running it by double-clicking the file in Explorer, right? 您更有可能通过双击资源管理器中的文件来运行它,对吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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