程序由于某种原因挂起

Program hangs because of some reason

本文关键字:挂起 由于某种原因 程序      更新时间:2023-10-16

下面的代码应该从输入中读取记录,并将它们存储在一个名为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<<"nn";
    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中的记录

如果您试图忽略在实际数据之后输入的新行字符,则必须使用:

std::cin.ignore();

如果您想要更多关于使用ignore的参考,请访问此链接