outfile.close();
}
intmain()
{
createfile();
return0;
}
实验结果:
代码分析:
定义两个函数judge、create。
分别实现判断素数,及创建文件的功能。
Create中调用judge函数,判断judge为1时该数是素数,将次数存入文件,同时定义一个计数的变量,当变量为5的倍数时换行,从而保证文件中是5个数一行。
在主函数中调用函数。
7.编写一个程序,可以读入一个C++语言的源文件,每一行加上行号后保存到另一个后缀为.prn的同名文件中,同时输出到屏幕上。
实验代码:
#include
#include
#include
usingnamespacestd;
voidkeep()
{
strings,name,name1;
cout<<"请输入c++源文件的名称(不含有后缀名)";
cin>>name;
name1=name+".prn";
name+=".cpp";
ifstreamread(name.c_str());
fstreamwrite;
write.open(name1.c_str(),ios:
:
trunk|ios:
:
out);
inti=0;
if(!
read)
{
cout<<"Cannotopeninputfile\n";
}
if(!
write)
{
cout<<"Cannotopenoutputfile\n";
}
while(getline(read,s))
cout<
write<<++i<
read.close();
write.close();
cout<<"目标文件生成成功(和源文件同目录)"<}
intmain()
{
keep();
return0;
}
代码分析:
定义一个函数主要实现打开、输出、保存的功能。
在函数中定义一个name的字符指针