c++ - c++中读写函数的问题
问题描述
我也面临 C++ 和 C 中的读写函数的问题。
当我在我的代码中输入 2 或更多name
和id
s 时,它会将其完美地写入文件,但是当我用它读取文件时,fread
它会显示一些奇怪的行为,它会打印相同的id
s 值,因为我输入不同的输入,但对于名称,它会打印相同的字符串对于我最后输入的所有不同长度的输入。
例子:
输入:
2
aaa 1
bbbb 2
输出:
ID 1 Name bbb
ID 2 Name bbbb
它应该像这样打印:
ID 1 Name aaa
ID 2 Name bbbb
我的代码:
#include <bits/stdc++.h>
using namespace std;
struct person
{
int id;
string fname;
};
int main () {
FILE *outfile;
struct person input;
int num,ident;
string sname;
outfile = fopen ("C:\\Users\\Amritesh\\Desktop\\students.txt","w+");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
scanf("%d",&num);
for(int i=0;i<num;i++){
cin >> sname;
scanf("%d",&ident);
struct person student = {ident,sname};
fwrite (&student, sizeof(struct person), 1, outfile);
}
fseek(outfile,0,SEEK_SET);
while(fread(&input, sizeof(struct person), 1, outfile)) {
cout << "ID " << input.id << " Name " <<input.fname << endl;
}
fclose (outfile);
return 0;
}
感谢您提前回答。
解决方案
推荐阅读
- nusmv - NuSMV CTL 规范
- tensorflow - 检查模型目标时出错:您传递给模型的 Numpy 数组列表不是模型预期的大小
- java - JAVA Eclipselink 查询
- java - 在列表中查找前 4 个最常见的对象
- mongodb - 如何向存储在 mongo 集合中的字符串格式存储的所有日期添加年份
- amazon-web-services - Amazon SNS 推送通知 - 单击推送后重定向到 Web url
- heroku - 如何根据另一个值设置运行时环境变量
- reporting-services - 用于年度比较的 SSRS 列组
- python-3.x - 如何为 tkinter 画布对象上的“条”设置动画以模拟排序算法的运行?
- shell - zsh:如果已定义,则打印带有周围文本的变量?