c++将代码运行结果打印要txt文件

如一个通讯录代码运行结果打印到记事本,那个txt文件放哪里,用VS运行的,改如何做


#include <iostream>
using namespace std;
#include <string>
#include <fstream>
int main()
{
 string s1="2000";
 ofstream of; //定义输出流;
 ifstream If; //定义只读取文件;
 of.open("e:\\123.txt");               //打开文件
 of << "利用ofstream的字符串是:" << s1 << endl;           //被读取的信息
 of.close();

 return 0;
}

你随便,只要规定好一个位置,从那里保存也从那里读取就行

可以试试文件操作,代码里写上
freopen("xxx.txt","w",stdout);
结尾加上
fclose(stdout);
题主应该是这个意思吧

只写文件名不带路径的话默认是从当前项目文件夹里寻找。若要将文件创建到指定的文件夹下,则在fopen()函数中的文件名带上路径名就可以了。但,如果程序对该文件夹没有操作权限,则fopen()会返回NULL。此外如果以不能自动创建文件的方式打开文件不存在则会报错。
温馨提示:
1.还需要注意保持读和写的方式是一样的否则可能会出错。
2.如果一次读取的数据量太多可能会导致内存暴涨,建议多次少量的读/写


#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
 
int main()
{
    int a[2][3] = { 1, 2, 3, 4, 1,2};
    float b = 11.1;
 
    // 向txt文档中写入数据
    ofstream dataFile;
    dataFile.open("dataFile.txt", ofstream::app);
    fstream file("dataFile.txt", ios::out);
 
 
    dataFile << a[1][1] << ' '<< b << endl;     // 写入数据
    dataFile.close();                           // 关闭文档
 
}

随便放哪里都可以,要读取的时候加上路径就行了

直接保存吧,要用再打开嘛

  • 您可以去学一下C语言相关的文件操作,看鹏哥的就好了,这个txt文件放的位置就是你cpp文件运行的根目录下,也就和代码文件放在同一目录下即可,vs比较复杂,可以用DEV - C++试试,很方便,

  • 写到根目录下可以用w(新建并写入)或w+(新建并读写)不要忘了开头的fopen()和结尾的fclose(),可以参照一下下面的这段代码

    int main(void) {
      FILE *fp1, *fp2;
      char ch;
      if ((fp1 = fopen("f12-2.txt", "r")) == NULL) {
          printf("File open error!\n");
          exit(0);
      }
    
      if ((fp2 = fopen("f12-3.txt", "w")) == NULL) {
          printf("File open error!\n");
          exit(0);
      }
    
      while (!feof(fp1)) {            //文件pf1是否结束
          ch = fgetc(fp1);            //读出文件fp1到ch
          if (ch != EOF)
              fputc(ch, fp2);            //将ch中存放的内容写到fp2中
      }
    
      if (fclose(fp1)) {            //关闭文件pf1
          printf("can't close the file\n'");
          exit(0);
      }
    
      if (fclose(fp2)) {            //关闭文件pf2
          printf("can't close the file\n'");
          exit(0);
      }
      
      return 0;
    }
    

    这是对应的根目录下的txt文件

img


希望对您有帮助