繁体   English   中英

如何使用变量作为文件名?

[英]How to use a variable as a files name?

我一直致力于一个创建信息并将信息存储到文件中的程序。 我唯一的问题是阻止我走得更远是文件名。 我可以手动命名文件但我不能使用变量(任何会做:数字,字符什么)的文件名和文件的内容。 这里有4行代码,这些代码现在已经让我开了一段时间了:

ofstream file;
file.open ("txt.txt"); \\I can manually create names, but that's not what I'm after
file.write >> fill; \\I attempted to use a 'char' for this but it gives errors based on the "<<"
file.close(); 

这是我第一次使用这个网站。 提前抱歉。

这真的取决于? C ++ 11还是C ++ 03?

首先创建一个string

std::string fname = "test.txt";

在C ++ 11中,您可以这样做:

file.open(fname);

但是在C ++ 03中,您必须:

file.open(fname.c_str());

您可以使用字符串类型的变量,并要求用户输入键盘来命名文件并填写内容。

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char** argv) {

    string fileName;
    string contents;

    cout << "What would you like the file name be? : ";
    cin >> fileName;

    cout << "\nPlease write the contents of the file: ";
    cin >> contents;

    ofstream file;
    file.open(fileName.c_str());        // provide the string input as the file name
    if(file.is_open()){ // always check if the program sucessfully opened the file
        file << contents << endl; // write the contents into the file
        file.close();   // always close the file!
    }

    return 0;
}

请注意,此程序将读取用户对内容的输入,直到它到达换行符'\\n'或空格' ' 所以如果你写HELLO WORLD! 作为内容的输入,它只会读取HELLO

我将留下如何阅读包括空格在内的整行作为练习。 我还建议你拿一本C ++书来学习文件输入/输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM