dimanche 3 septembre 2017

Input from txt file doesn't match when it is read/passed second time (C++)

So I am fairly new to coding and c++. So...sorry if this is something very obvious to some of you:

I am having a hard time getting this code to read the input stored in txt file for a second time. It works for the first time.

void readcode(ifstream& infile, int list[], int& length, bool& lenCodeOk)
{
    int count;
    lenCodeOk = true;

    infile >> length; //get the length of the secret code
    cout << "Length1 is "<<length<<endl;


    if (length > MAX_CODE_SIZE)
    {
            lenCodeOk = false;
            return;
    }
            //Get the secret code.

    for (count = 0; count < length; count++)
    {
            infile >> list[count];
    }

    cout<<" Code recorded is: ";
    for (count = 0; count < length; count++)
    {
            cout<<list[count]<<" "<<endl;
    }
}

So the first integer in my txt file is the length of the sequence of integers. This function does everything it is supposed to. Reads the length correctly also stores everything in an array.

However when I call the below compareCode function after calling the readcode function, it comes out with a completely random/different length2 (that changes/goes one up everytime I call) and array elements.

void compareCode(ifstream& infile, ofstream& outfile, const int list[], int length)
{

    int length2;
    int digit;
    bool codeOk;
    int count;

    codeOk = true;

    infile >> length2;

    cout<<"Length2 is "<<length<<endl;


    if(length != length)
    {
            cout<< "The original code and its copy are not of the same length"<<endl;
            return;
    }


    outfile << "Code Digit    Code Digit Copy"<<endl;
    for (count= 0; count<length; count++)
    {
            infile >> digit;
            outfile<<setw(5)<<list[count]<<setw(17)<<digit;

            if (digit != list[count])
            {
                    outfile << " Code digits are not the same"<<endl;
                    codeOk = false;
            }
            else
            {
                    outfile<<endl;
    }

            if (codeOk)
            {
                    outfile<<"Message transmitted OK."<<endl;
            }
            else
            {
                    outfile<<"Error in transmission. "<<"Retransmit!!"<<endl;

              }

    }
}

It seems like I am missing an important piece of information about passing fstream variables I would really appreciate if someone pointed me towards the right direction.

Aucun commentaire:

Enregistrer un commentaire