在矢量错误中输入和输出文件中的数据

Inputting and Outputting Data from file in Vector Error?

本文关键字:输出 文件 数据 输入 错误      更新时间:2023-10-16

我对C++相当陌生,我不确定为什么我的输出文件是空白的。 我认为这可能与我的功能有关?当我只是将代码放入 main 而不是函数时,输出文件会给我信息。我不确定我做错了什么。

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
#include <vector>
#define die(msg) {cerr << msg << endl; exit(1);}
using namespace std;
struct Eip
{
    string block;
    string blkSfx;
    string lot;
    string lotSfx;
};
void inputData(fstream &, vector<Eip>);
void outputData(fstream &, vector<Eip>);
int main()
{
    fstream fs("Book1.txt", ios::in);
    fstream fsout("SecuredEIP.txt", ios::out);
    if(!fs.is_open()) die("Can not open Book1.txt!");
    if(!fsout.is_open()) die("Can not open SecuredEIP.txt!");
    vector<Eip> name;
    inputData(fs, name);
    outputData(fsout, name);
    fs.close();
    fsout.close();
    return(0);
}
void inputData(fstream &fs, vector<Eip> name)
{
    while(fs) {
        Eip temp;
        getline(fs, temp.block, 't');
        getline(fs, temp.blkSfx, 't');
        getline(fs, temp.lot, 't');
        getline(fs, temp.lotSfx, 'n');
        name.push_back(temp);
    }
}
void outputData(fstream &fsout, vector<Eip> name)
{
    for(int i = 1; i < name.size(); i++) {
        fsout << setw(4) << setfill('0');
        fsout << name[i].block;
        if(name[i].blkSfx == "")
            fsout << " ";
        else
            fsout << name[i].blkSfx;
        fsout << setw(3) << setfill('0');
        fsout << name[i].lot;
        if(name[i].lotSfx == "")
            fsout << "  " << endl;
        else
            fsout << name[i].lotSfx << " " << endl;
    }
}

这是我的文本文件中的数据。

3965    1   
837     9   
3749    59  
3752    19  
3532    54  
6769    49  
535     10  
819     13  B
3616    84  
26      30  
3732    8   
3732    150 
6536    8   
71      2   

您正在将向量的副本传递给 inputData/outputData - 改为进行这些引用,即更改:

void inputData(fstream &fs, vector<Eip> name)

void outputData(fstream &fsout, vector<Eip> name)

自:

void inputData(fstream &fs, vector<Eip> &name)

void outputData(fstream &fsout, vector<Eip> &name)