无法将输出写入cpp程序中的文本文件

Cannot write the output to a text file in cpp program

本文关键字:程序 文本 文件 cpp 输出      更新时间:2023-10-16

我有这个输入文件"https://code.google.com/codejam/contest/351101/dashboard/do/A-large-practice.in?cmd=GetInputFile&问题=374101&input_id=1&filename=A-大练习.in&redownload_last=1&agent=网站&csrfmiddlewaretoken=OWMxNTVmMTUyODBiYjhhN2Q2OTM3ZGJiMTNhNDkwMDF8fDEzNzIxNzI1NTE3ODAzMjA%3D"我试着读取这个文件:-使用freopen("filename.txt",r,stdin);然后我想把写的输出写到另一个文本文件中,我可以在这个代码堵塞练习题中上传给法官。

#include<iostream>
   #include<cstdio>
   using namespace std;
   int main()
   {
     int t,k=0,a[2000];
     freopen("ab.txt","r",stdin);
     scanf("%d",&t);
     while(t--)
     {
         freopen("cb.txt","w",stdout);
         int c;
         scanf("%d",&c);
         int n;
         scanf("%d",&n);
         for(int i=0;i<n;i++)
         scanf("%d",&a[i]);
         printf("Case #%d: ",++k);
         for(int i=0;i<n-1;i++)
         {for(int j=i+1;j<n;j++)
          if((a[i]+a[j])==c)
           {printf("%d %dn",i+1,j+1);
             i=n;}
           }
     }
     return 0;
    }

这是我的密码。现在的问题是输出文件cb.txt只包含输入的最后一行。我希望将整个输出写入cb.txt,那么我该怎么办。

您可能将控制台输入(scanf)与文件输入(fscanf)混淆。

文件I/O的C样式函数有一个f前缀
参见:fprintf, fscanf, fgets, and fputs

我弄错了,我放了freopen("cb.txt","w",stdout);在循环中,所以每次输出都被覆盖,现在我把这行放在循环外,它就可以工作了