About the pause of C++ win32 console application

本文介绍在C++控制台应用程序中实现程序暂停的方法,包括使用system("PAUSE")、getchar()及Sleep()等函数,并提供了一个在程序退出前保持窗口不关闭的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

想要使C++控制台应用程序暂停,呈现命令行窗口的办法有如下几种:

一、针对Microsoft

#include   <stdlib.h> 

(1)第一种方式
system( "PAUSE "); 
-------------------- 
(2)第二种方式
getchar();  // 这招对QT程序也有用
--------------------- 
(3)第三种方式
Sleep();


二、针对Linux
(1)第一种方式

getchar();

But,如何使程序在return 0之后暂停下来呢?终极解决方法是:
用_onexit注册 回调函数,该函数可以在 main函数结束之后调用.
下面举个栗子!

StringX.h文件:

#pragma once
#include <stdio.h>

class StringX
{
public:
 StringX(const char *str = NULL); //普通构造函数
 StringX(const StringX &other);  //复制构造函数
 ~StringX(void);         //析构函数
 StringX & operator=(const StringX &other); //赋值函数
private:
 char *m_StringX;        //私有成员,保存字符串
};

#include "StringX.h"
#include <iostream>
#include <stdlib.h>
using namespace std;

StringX::~StringX(void)
{
 cout<<"析构函数"<<endl;
 if (m_StringX!=NULL)
 {
  delete [] m_StringX;
  m_StringX=NULL;
 }
}

StringX::StringX(const char *str)
{
 cout<<"构造函数"<<endl;
 if(str==NULL)       //如果str为NULL,存空字符串""
 {
  m_StringX=new char[1];  //分配一个字节
  *m_StringX='\0';     //将之赋值为字符串结束符
 }
 else
 {
  m_StringX=new char[strlen(str)+1];  //分配空间容纳str内容
  strcpy(m_StringX,str);        //复制str到私有成员
 }
}

StringX::StringX(const StringX &other)
{
 cout<<"复制构造函数"<<endl;
 m_StringX=new char[strlen(other.m_StringX)+1]; //分配空间容纳str内容
 strcpy(m_StringX,other.m_StringX); //复制str到私有成员
}

StringX & StringX::operator=(const StringX &other)
{
 cout<<"赋值函数"<<endl;
 if (this==&other)    //如果对象与other是同一个对象
 {
  return *this;     //直接返回本身
 }
 delete [] m_StringX;  //释放堆内存
 m_StringX=new char[strlen(other.m_StringX)+1];
 strcpy(m_StringX,other.m_StringX);
 return *this;
}

int fn(void)
{
 system("PAUSE");
 return 0;
}

int main()
{
 _onexit(fn);     //用_onexit注册回调函数,该函数可以在main函数结束之后调用
 StringX a("Hello");  //调用普通构造函数
 StringX b("World");  //调用普通构造函数
 StringX c(a);     //调用复制构造函数
 c=b;        //调用赋值函数
 return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值