首页 > 解决方案 > 如何保存数据,用户指定

问题描述

这是一个需要将输出保存到用户指定的数据文件的程序,但它似乎没有保存,我不知道为什么,我对 C++ 相对较新,因此感谢您的帮助

cout << "Press 's' then 'Enter' to save the file or any other key then 'Enter' to display";
cin >> save;

if (save != 's')
{
    cout << "Ix = " << Ix << "A\n";
    cout << "Iy = " << Iy << "A\n";
    cout << "Vz = " << Vz << "V\n";
}
else
{
    cout << "Please enter a name for your file: \n";
    cin >> filename;

    cout << " Please enter a directory to save your file in: \n";
    cin >> filepath;

    ofstream file((filepath + "/" + filename).c_str());

//input is being writen to the file
    file << "Ix = " << Ix << "A\n";
    file << "Iy = " << Iy << "A\n";
    file << "Vz = " << Vz << "V\n";

    file << flush;
    file.close();
}

}

标签: c++save

解决方案


欢迎来到SO。

打开文件流时,您首先必须检查打开操作是否成功。
你可以这样做:

if(!file) { /* file isn't "good", open seems to have failed */}
/* or */
if(!file.good()) { /* file isn't good */ }

我猜,因为它没有向文件写入任何内容(也没有创建文件?)该目录可能不存在。
该类std::ofstream不会自动创建所需的目录。
您如何创建所需的目录在这里得到了很好的解释:https ://en.cppreference.com/w/cpp/filesystem/create_directory


推荐阅读