c++ - 如何保存数据,用户指定
问题描述
这是一个需要将输出保存到用户指定的数据文件的程序,但它似乎没有保存,我不知道为什么,我对 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
推荐阅读
- react-native - 如何仅渲染数组中的第一个对象?React Native 扁平列表
- python - 简化 Python 中的条件语句
- python - Python嵌套for循环排序
- c++ - ReadProcessMemory 总是读取 0
- python - 从条纹中检索所有具有嵌套价格的产品?
- ruby - 更新到 Catalina 后无法安装 Jekyll - 安装 ffi (1.9.18) 时出错
- ruby-on-rails - 在 Rails 中查找数据库字段之间的平均/最小/最大操作
- angular - 角度反应式表单数组将第一个索引值作为空对象返回
- ios - 错误消息:线程 1:EXC_BAD_ACCESS(代码=2,地址=0x7ffeead03e18)
- javascript - 如何让 webpack-dev-server 在 mac 上打开 Brave