c++ - 写入/创建文件 C++ 时遇到问题

标签 c++ file-io

我正在制作一个程序,它接受输入并将其打印到一个文本文件中,并为其提供创建日期的名称,有点像数字日记。但是,当 VS 中的 f5 开始时没有错误,运行时就好像一切都很好,然后当我检查它是否已创建文件时,它在项目文件夹中无处可寻。提前感谢您的帮助。

        string date;
        time_t now;
        struct tm nowlocal;
        now = time(NULL);
        nowlocal = *localtime(&now); 
        int year = nowlocal.tm_year + 1970; 
        date = to_string(nowlocal.tm_mday) + ":" + to_string(nowlocal.tm_mon) + ":" + to_string(year) + ".txt";
        char write[900];
        ofstream file;
        file.open(date);
        cout << "input text to write to the journal(900chars max):";
        cin >> write;
        file << write << endl;
        file.close();

最佳答案

我认为您的主要问题是您的命名约定。 : 不允许出现在文件名中,因此您的文件未被创建。还有一些其他错误。您还需要弄乱您的 char 数组。

#include <iostream>
#include <ctime>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    string date;
    time_t now;
    struct tm nowlocal;
    now = time(NULL);
    nowlocal = *localtime(&now);
    int year = nowlocal.tm_year + 1970;
    date = to_string(nowlocal.tm_mday) + "_" + to_string(nowlocal.tm_mon) + "_" + to_string(year) + ".txt";  //changed all ':' to '_'
    //char write[900];
    string write;
    cout << date << endl;
    ofstream file(date);
    //file.open(date);          //this was also causing an error
                                //your file is already open 
    cout << "input text to write to the journal(900chars max): ";

    getline(cin, write);
    //cin >> write;

    file << write << endl;
    file.close();




    system("PAUSE");
    return 0;
}

我修正了一些错误。它现在似乎正在工作。我不得不使用字符串而不是您使用的数组。在类里面这样做,所以你可以在我的代码中预料到一些错误哈哈。希望这有帮助!祝你好运!

关于c++ - 写入/创建文件 C++ 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922664/

相关文章:

c++ - 像结构成员一样访问 C++14 lambda 捕获

node.js - 异步将数据追加到文件

java - 在 Java SE 6 中 move 文件并进行错误处理

c++ - 获取当前 TTS 语音的语言

c# - 一个低开销的文件写入过程应该在它自己的线程上吗?

java - 如何从另一个类访问 arrayList (存储在主类中)?

c++ - 如何在 C++ 中创建缓冲区以创建新文件

c++ - 使用 makefile 有什么好的理由吗?

c++ - 如何在 C++ 矩阵 2D 的其他对角线上找到平行对角线反转

android - 缺少虚拟析构函数内存效应