c++中怎么样把输出保存到文档中?

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int a[20][2001];
int ans[500][3];
int main()
{
int i,j,cnt,k,l,m,n,q,w,e,r;
freopen("left.in","r",stdin);
//freopen("left.out","w",stdout);
cnt=0;
for (i=1;i<=19;i++)
for (j=1;j<=1980;j++)
{
scanf("%d",&a[i][j]);
}
for (i=1;i<=19;i++)
for (j=i+1;j<=19;j++)
{
l=0;
for (k=1;k<=1980;k++)
{
if (a[i][k]==a[j][k])
l++;
}
if (l>=1584)
{
cnt++;
ans[cnt][1]=i;
ans[cnt][2]=j;
}
}
for (i=1;i<=cnt;i++)
{
printf('data.txt',"%d %d\n",ans[i][1],ans[i][2]);
}
fclose(stdin);
fclose(stdout);
return 0;
}

你的程序,基本都没有问题,借助你原来的程序就能完成:

1、把下面这句启用:

    freopen("left.out","w",stdout);

2、循环内的 'data.txt'  改成 stdout ,变成下面这样:

for (i=1;i<=cnt;i++)
{
    fprintf(stdout,"%d %d\n",ans[i][1],ans[i][2]);
}

修改后的程序是:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int a[20][2001];
int ans[500][3];
int main()
{
int i,j,cnt,k,l,m,n,q,w,e,r;
freopen("left.in","r",stdin);
freopen("left.out","w",stdout);
cnt=0;
for (i=1;i<=19;i++)
for (j=1;j<=1980;j++)
{
scanf("%d",&a[i][j]);
}
for (i=1;i<=19;i++)
for (j=i+1;j<=19;j++)
{
            l=0;
for (k=1;k<=1980;k++)
{
if (a[i][k]==a[j][k])
l++;
}
if (l>=1584)
{
cnt++;
ans[cnt][1]=i;
ans[cnt][2]=j;
}
}


{
    fprintf(stdout,"%d %d\n",ans[i][1],ans[i][2]);
}
fclose(stdin);
fclose(stdout);
return 0;
}

 运行结果,保存到文件的一部分:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-13

#include <stdio.h>

#include <math.h>

#include <string.h>

#include <iostream>

#include <algorithm>

#include<fstream>

using namespace std;

int a[20][2001];

int ans[500][3];

int main()

{

int i,j,cnt,k,l,m,n,q,w,e,r;

freopen("left.in","r",stdin);

//freopen("left.out","w",stdout);

cnt=0;

for (i=1;i<=19;i++)

for (j=1;j<=1980;j++)

{

scanf("%d",&a[i][j]);

}

for (i=1;i<=19;i++)

for (j=i+1;j<=19;j++)

{

            l=0;

for (k=1;k<=1980;k++)

{

if (a[i][k]==a[j][k])

l++;

}

if (l>=1584)

{

cnt++;

ans[cnt][1]=i;

ans[cnt][2]=j;

}

}

/////////////here /////////////

ofstream offile("data.txt");


for (i=1;i<=cnt;i++)

{

//printf('data.txt',"%d %d\n",ans[i][1],ans[i][2]);


offile<<ans[i][1]<<" "<<ans[i][2]<<endl;

}

fclose(stdin);

fclose(stdout);

return 0;

}


第2个回答  2013-09-13
#include<fstream>

........

ofstream xxx("x:\\xxx.txt");
if(!xxx)return;
xxx<<setw(20)<<"ilove"<<"xxx"<<endl;
f1.close();

这么简单就不用解释了吧追问

您好,能不能帮忙套到程序里?我是初学者,确实不懂

追答

我建议你,多百度,多自己尝试,有人给了你应该用什么,有了方向一定要自己尝试,错了,要搞明白为什么错了,对了,去研究研究头文件,为什么这样就是对的,这样才会有进步,如果自己不尝试总是去看正确的范本,那么最终你的导向(或者说倾向?)会变成一个最低级的码农,说白了,告诉你把砖搬到三楼,你甩甩肩膀就去搬了,永远不会知道为什么要把砖搬到三楼,我不是做it行业的,只是个人兴趣谈谈自己的看法,个人感觉我写这么一大堆远比把那么简单几句代码加进去要辛苦,希望你能理解我的意思,也希望对你会有帮助

相似回答