c++ - 防止控制台窗口在返回值后自行关闭

标签 c++

我是 C++ 新手。我的第一个应用就是这样。

#include "stdafx.h"
#include <iostream>
using namespace std;
int add (int x, int y);

int add (int x, int y){
return (x+y);
}
int _tmain(int argc, _TCHAR* argv[])
{
    int x, y;
    cin >>x>>y;
    cout <<add (x,y);
    cin.get();
    return 0;
}

有 2 个问题:

  1. 即使我使用了 cin.get();,为什么控制台窗口会在函数返回值后直接关闭?
  2. 我在文件顶部没有 int add (int x, int y); 行的情况下测试了这个应用程序。它运作良好。我是否需要为每个功能或应用程序编写原型(prototype)而不需要它?

最佳答案

问题 1:cin >>x>>y 在输入缓冲区中留下一个换行符,它被 cin.get 读取,导致它继续.

尝试

cin.sync(); //remove unread characters
cin.get(); //read one character (press enter)

问题 2:原型(prototype)存在,因此您可以让编译器知道该函数存在,然后使用该函数(比如在 main 中),然后稍后定义函数体(比如在 main 之后)。

int add (int, int); //compile error if left out

int main()
{
    add (3, 4);
}

int add (int a, int b)
{
    return a + b;
}

关于c++ - 防止控制台窗口在返回值后自行关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10262942/

相关文章:

c++ - 将 << 运算符重载为 "friend"函数以打印 BST - C++

c++ - 从 Vector3f 访问数据

c++ - 对于简单的矩阵乘法,OpenCL CPU 比 OpenCL GPU 更快

c++ - opencv 中的 StereoBM 类是否对输入图像或帧进行校正?

c++ - 没有有用信息的 GLSL 链接失败

C++ vector 随机洗牌它的一部分

c++ - 为什么这个用两个参数声明的构造函数可以只用一个参数调用?

c++ - 我应该在读取数组大小后声明一个数组吗?

c++ - 通过与 bimap 键类型不同的类型在 boost::bimaps::bimap 中查找元素

C++ 变量声明语法