程序由于某种原因挂起
Program hangs because of some reason
下面的代码应该从输入中读取记录,并将它们存储在一个名为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文件。。
您可以通过
如果您试图忽略在实际数据之后输入的新行字符,则必须使用:
std::cin.ignore();
如果您想要更多关于使用ignore
的参考,请访问此链接
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 由于某种原因,WriteProcessMemory无法正常工作
- 我有一个应该打印数组的函数,但由于某种原因它不起作用
- 在矩阵逆变器上工作,由于某种原因,我的指数循环不起作用
- 由于某种原因,我的代码中出现了 [json.exception.type_error.302]。我知道错误意味着什么,但我不知道哪里有故障
- 由于某种原因,客户端未调用服务器 RPC
- 由于某种原因,我无法创建 GLFW 上下文
- 由于某种原因,多维数组不会从函数中更改元素
- 由于某种原因,用浮子的乘法是错误的
- "total += i;"由于某种原因不起作用
- C++ 由于某种原因,我无法让模板在链表中工作,我敢打赌这是一个简单的错误,但我就是不明白
- 我是初学者,由于某种原因,这不起作用,我正在使用视觉工作室
- C++:当我输入一个字符串时,由于某种原因,程序期望更多,并导致整个代码出现问题
- 由于某种原因,FSTREAM测试程序崩溃
- XNextEvent 由于某种原因不起作用
- 由于某种原因,必须发送两次 MPI 消息
- 由于某种原因,使用 OR 运算符执行操作不起作用
- 将短文转换为二进制..由于某种原因,前 8 位数字和后 8 位数字被交换
- 程序由于某种原因挂起
- 由于某种原因,设置函数不起作用