我目前在课堂上使用Putty虚拟机(UNIX),并且正在做简短的C ++作业。任务是:“创建一个C ++程序,该程序进行测试以查看文件帐户是否存在并打印一条消息以说明文件是否存在”
这就是我所拥有的,但是当我尝试编译代码时,出现此错误:error:':: main'必须返回'int'
#include<iostream>
#include<fstream>
using namespace std;
inline bool exists_test1 (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
void main()
{
string s;
cout<<"Enter filename";
cin>>s;
bool ans =exists_test1(s);
if(ans)
{
cout<<"File Exist"<<endl;
}
else
{
cout<<"File Does not Exist";
}
}
Run Code Online (Sandbox Code Playgroud)
的返回类型main
为int
。这是由C ++标准定义的。在C ++ 11草案的本地副本中,第3.6.1节Main Function中对此进行了概述:
实现不得预定义主要功能。此功能不得重载。它的返回类型应该是int类型,否则它的类型是实现定义的。所有实现均应允许以下两个main定义:
Run Code Online (Sandbox Code Playgroud)int main() { /* ... */ }
和
Run Code Online (Sandbox Code Playgroud)int main(int argc, char* argv[]) { /* ... */ }
因此,根据标准,您的程序格式错误,并且编译器正确地将其报告为错误。将函数定义为:
int main()
{
// your code...
return 0;
}
Run Code Online (Sandbox Code Playgroud)