为什么我的这段代码不能写入文件
Why won't this piece of my code write to file
我正在开发一个C++银行系统。我能够正确获取浮点数、newbal 值,当我尝试写入文件时,文件中没有数据。
else if (x == 2)
{
cout << "You have selected option number 2. Deposit.n";
cout << "Please enter you account ID: ";
cin >> ID;
file.open("C:\Users\Raggulddon\Desktop\C++ supplement\Cust_" + ID + ".dat", ios:: in | ios::out | ios::binary);
if (!file)
{
cout << "Sorry the requested account could not be located.n";
}
else
{
file >> firstname >> lastname;
cout << endl << firstname << " " << lastname << endl;
cout << "-----------------------------------n";
string line;
while (getline(file, line))
{
// stringstream the getline for line string in file
istringstream iss(line);
if (iss >> date >> amount)
{
cout << date << "tt$" << showpoint << fixed << setprecision(2) << amount << endl;
famount += amount;
}
}
cout << "Your balance is $" << famount << endl;
cout << "How much would you like to deposit today: $";
cin >> amountinput;
float newbal = 0;
newbal = (famount += amountinput);
cout << "nYour new balance is: $" << newbal << ".n";
file << date << "tt" << newbal; //***This should be writing to file
but it doesn 't.
file.close();
文本文件如下所示:
托尼·加迪斯
12-05-24 100
12-05-30 300
12-01-07 -300
控制台输出如下所示
托尼·加迪斯
12-05-24 100
12-05-30 300
12-01-07 -300
您的余额为:#1
您想存入多少:#2
您的新余额是: #1 + #2
写入文件
关闭文件。
退出主循环::::
如何使其写入文件并保存,以及为什么会发生这种情况。
考虑到如何使用istringstream
输入,我也尝试使用ostringstream
来执行此操作。但它也没有用:
float newbal=0;
newbal = (famount += amountinput);
ostringstream oss(newbal);
oss << date << "tt" << newbal;
我正在尝试自学C++因此任何相关信息将不胜感激。
如果要
编写文本文件,则在打开文件时不应使用"ios::binary"。
相关文章:
- 为什么头文件不能相互包含?
- 为什么我可以从C++文件中读取 int 值,但不能浮点?
- 为什么我不能从同一目录中的另一个文件中 #include 我的类?
- CStdioFile 不能处理大于 2GB 的文件?
- 不能在其他文件中包含结构
- 有没有办法关闭文件? fclose 不能很好地工作
- 我的项目中某些仅标头文件不能包含使用 CMake 和 Vscode 的"SFML/Graphics.hpp"
- OpenGL不能在核心配置文件中使用glVertexAttrib进行绘制
- 我可以在Windows(Visual C++)中读取bin文件,但不能在linux(GCC)上读取bin文件
- 为什么我不能将 Windows 环境路径与 ofstream 一起使用来编写文本文件?
- C++不能使用其他文件中的类
- 为什么我不能编译这个在Cygwin的Visual Studio中编写的C++文件?
- 为什么我不能像C++中的小端序文件那样读取大端 ELF 文件?
- 我可以固定C 可执行文件,但不能共享库
- 为什么将可执行文件重命名为临时文件的此代码段不能按预期工作?
- 为什么SDL_RWFromFile(文件,"w+")不能像它应该的那样读写?它只打开文件进行写入
- 不能在 dlib cpp 文件中包含JPEG_SUPPORT标头
- C 能够以其完整路径打开代码::块中的文件,但不能以相对路径作为命令行参数打开文件
- 无法使用名称空间,也不能在我的.h文件中包含标准的C 库
- 不能从文件到指针向量的对象复制