gpt4 book ai didi

c++ - 程序由于某种原因挂起

转载 作者:搜寻专家 更新时间:2023-10-31 01:15:44 24 4
gpt4 key购买 nike

以下代码应该从输入中读取记录并将它们存储在名为 file.dat 的文件中。然后它应该按升序排列这些记录,但由于某种原因程序在第二个 while 循环中挂起在行“file1.seekg(-(sizeof(r)),std::ios::cur);”。谁能告诉我哪里出了问题?

#include <iostream>
#include <fstream>
#include <strstream>

int main()
{
std::ofstream file;
file.open("file.dat",std::ios::trunc|std::ios::binary);
if(!file)
std::cout<<"unable to open for output";

struct record
{
char code[6];
char name[20];
int i;
};

record r;
int a = 0;

while(1)
{
std::cout<<"Record " << a + 1 << std::endl;
std::cout<<"Enter character code, name and an int \n";
std::cin.ignore();
std::cin.getline(r.code,6);
std::cin.getline(r.name,20);
std::cin>>r.i;
file.write((char *)&r,sizeof(r));
std::cout<<"\nAdd another (y\\n) : ";
char c;
std::cin>>c;
if(c == 'n')
break;
a++;
std::cout<<'\n'<<'\n';
}
file.close();

std::fstream file1("file.dat",std::ios::in|std::ios::out|std::ios::binary);
if(!file1)
std::cout<<"unable to open file1";

else
{
if(a>0)
{ while(a)
{
file1.seekp(0);
for(int i = a; i>0;i--)
{
record r1;
file1.read((char *)&r,sizeof(r));
file1.read((char *)&r1,sizeof(r1));
if(r1.i < r.i)
{
file1.seekp(-(sizeof(r)*2),std::ios::cur);
file1.write((char *)&r1,sizeof(r));
file1.write((char *)&r,sizeof(r));
file1.seekg(-(sizeof(r)),std::ios::cur);
}
}

a--;
}
}
file1.close();
}

std::ifstream file2("file.dat",std::ios::binary);
if(!file2)
std::cout<<"unable to open file2";
else
while(1)
{
std::cout<<"\n\n";
file2.read((char *)&r,sizeof(r));
if(file2.eof())
break;
std::cout<<r.code<<'\t'<<r.name<<'\t'<<r.i;
}
}

最佳答案

首先

更改 std::get.ignore -> std::cin.ignore()

如果你想丢弃一个字符。

它编译得很好并创建了 file.dat 文件..

虽然你可以检查 file.dat 中的记录

关于c++ - 程序由于某种原因挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9766325/

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