gpt4 book ai didi

c++ - 文件处理在 while 循环中不起作用

转载 作者:行者123 更新时间:2023-11-28 03:20:56 25 4
gpt4 key购买 nike

代码:

#include<iostream.h>
#include<fstream.h>
#include<string.h>
int n = 0, flag = 0,i;
struct bac
{
char name[10];
char amt[5];
} s;



void main()
{
ofstream f("C:\\TC\\1.dat");
for(i=0;i<10;i++)
{

cout << "\nenter the details ";
cin >> s.name >> s.amt;

f.write((char *)&s, sizeof(bac));
}
}

有时代码工作正常 但是其他时候,当我查看输出文件时,它是空的,问题出现了很多次,我想知道是否有关于文件处理循环的预防措施

例如。在其他程序中

.....
while(ch!=4)
{
cout << "\nBANK MANAGEMENT SYSTEM \n";
cout << "enter choice ";
cout << "\n1.add\n2.search\n3.delete and overwrite ";
cin >> ch;
if (ch == 1)
{
cout << "\nenter the details ";
cin >> s.name >> s.amt;
f.write((char *)&s, sizeof(bac));
}
.....

文件为空

最佳答案

我猜您可能使用了比 gcc 4.5.3 更早的非常旧的编译器。我试过你的代码,没问题。

#include <iostream>  //use header file without using deprecated iostream.h
#include <fstream> //same reason as above
#include <string>

using namespace std;


int n = 0, flag = 0,i;
struct bac
{
char name[10];
char amt[5];
} s;



int main() //usually main returns int. void was kind of old now
{
ofstream f("test.txt");
for(i=0;i<10;i++)
{

cout << "\nenter the details ";
cin >> s.name >> s.amt;

f.write((char *)&s, sizeof(bac));
}
f.flush();
f.close();

return 0;
}

我在 gcc 4.5.3 中编译了代码并运行了它。该文件包含我输入的所有内容。但是,当您使用文件 i/o 流写入文件时,最好使用 << 运算符。

您可以从该链接的顶部找到更多信息: http://members.gamedev.net/sicrane/articles/iostream.html

还有一点,当你完成文件写入后,记得刷新并关闭文件句柄,否则,有时会导致一些恼人的问题。

关于c++ - 文件处理在 while 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15462059/

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