本文介绍了如何创建名为变量的流文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char NAME[256];
cin.getline (NAME,256);
ofstream fout("NAME.txt"); //NAME???????

使用NAME名称创建文件需要做什么?

What i need to do to create file with NAME name?

推荐答案

您可以尝试:

#include <string>
#include <iostream>
#include <fstream>

int main() {
    // use a dynamic sized buffer, like std::string
    std::string filename;
    std::getline(std::cin, filename);
    // open file, 
    // and define the openmode to output and truncate file if it exists before
    std::ofstream fout(filename.c_str(), std::ios::out | std::ios::trunc);
    // try to write
    if (fout) fout << "Hello World!\n";
    else std::cout << "failed to open file\n";
}

一些有用的参考资料:







  • http://en.cppreference.com/w/cpp/string/basic_string
  • http://en.cppreference.com/w/cpp/string/basic_string/getline
  • http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream
  • http://en.cppreference.com/w/cpp/io/basic_filebuf/open
  • http://en.cppreference.com/w/cpp/io/ios_base/openmode

这篇关于如何创建名为变量的流文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 22:54