香辣炸鸡架的做法:C++中的递增

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/28 01:23:46
没事写了一个小东西。很简单,它会在你运行的位置创建1个.txt文档,和指定的位置创建n个.txt文档。(这只是目的,但我不能办到)因为有个小问题,大家先看代码:
#include <cstdlib>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
char filename[]="n.txt";

ofstream file_out(filename);
if(!file_out){
cout<<"file"<<filename<<"could not be opened.";
return -1;
}
cout<<"file"<<filename<<"was opened.";
file_out<<"开个小玩笑"<<endl;
file_out.close();
for(int i=0;i<=2;i++){
system("copy n.txt d:\\ ");}

return 0;
}
怎么让这里的n递增?(n.txt)如果能递增就能复制n个,如果不能那只能复制一个了,因为同一个文件名会被复盖。
这里关系到两个问题,1、怎样改变常量的值。
2 、怎样在dos下让这个值也改变。
如果这两个都解决了,那就可以开玩笑了

1.常量的值改变不了。不过你好像只用到了变量与数值常量。
2.
for(int i=0;i<=2;i++){
system("copy n.txt d:\\ ");}

改一下:
char *command="copy n.txt d:\\",*p;
for(int i=0;i<=2;i++){
strcpy (p,command);
strcat (command,"n");
strcat (command,i+'a');
strcat (command,".txt");
system(command);
strcpy (command,p);
}

建议你察看cout 和 os 两条命令的 区别,生成指定的文件很简单的

...

char s_path[512];/*定义一个字符串用来生成新的文件名*/

for(int i=0;i<=2;i++)
{
memset(s_path,0x0,sizeof(s_path));/*将字符串置空*/
sprintf(s_path,"copy n.txt d:\\n%d.txt",i);/*生成新的文件名*/
system(s_path);/*系统调用,拷贝文件*/
}
...

你可以先定义一个字符串,str=".txt"
然后再定义n, 改变n的值,将n与str连接成一个字符串,
最后将这字符串作为一个文件名,
现在就可以了吧