/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:呼亚萍
* 完成日期:2015年6月10日
* 版 本 号:v1.0
*
* 问题描述: 读入一个C++程序,判断其中是否只有一个main()函数,输出“暂时没有发现问题”,或者“没有main()函数”,或者“不能定义多个main()函数”;
* 程序输入:相应的程序
* 程序输出:对应得结果
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>//为了使用exit()
#include <fstream>
using namespace std;
int appear(char*s1,char*s2);
int main()
{
char line[256];
char main_fun[8]="main()";
int main_num=0;//初时,尚未发现
ifstream sourceFile("source.cpp",ios::in);//读入文件
if(!sourceFile)
{
cout<<"source.cpp can't open"<<endl;
exit(1);
}
while (!sourceFile.eof())
{
sourceFile.getline(line,255,'\n');//每行最多255个字符
main_num+=appear(line,main_fun);
if(main_num>1)//多于一个没必要再去读取
break;
}
sourceFile.close();
if(main_num==0)
cout<<"error:no main";
if(main_num==1)
cout<<"right:a main() be exited";
else
cout<<"error:more than one main()";
return 0;
}
int appear(char *s1,char *s2)
{
int n=0,flag;
char *p,*q;
for(; *s1!='\0'; s1++)
{
if(*s2==*s1)//判断字符串中是否有和要判断的字串首字符相同的字符
{
flag=1;
p=s1;
q=s2;
for(; *q!='\0';)
{
if(*q++!=*p++)
{
flag=0;
break;
}
}
if(flag==1)n++;
}
}
return (n);
}
运算结果:
知识点总结:
文件的读入与输出。
学习心得:
c++学习的新视野开拓!