首页 > 解决方案 > c++中读写函数的问题

问题描述

我也面临 C++ 和 C 中的读写函数的问题。

当我在我的代码中输入 2 或更多nameids 时,它会将其完美地写入文件,但是当我用它读取文件时,fread它会显示一些奇怪的行为,它会打印相同的ids 值,因为我输入不同的输入,但对于名称,它会打印相同的字符串对于我最后输入的所有不同长度的输入。

例子:

输入:

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;
} 

感谢您提前回答。

标签: c++filefile-handling

解决方案


推荐阅读