gpt4 book ai didi

c++ - 用户指定如何保​​存数据

转载 作者:行者123 更新时间:2023-12-02 10:03:55 24 4
gpt4 key购买 nike

这是一个需要将输出保存到用户指定的数据文件的程序,但是它似乎没有保存,而且我不确定为什么,我对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();
}

}

最佳答案

欢迎来到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

关于c++ - 用户指定如何保​​存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61206625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com