我是 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 个问题:
- 即使我使用了
cin.get();
,为什么控制台窗口会在函数返回值后直接关闭? - 我在文件顶部没有
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/