简体   繁体   中英

Object oriented programming get function doesn't return correct array

This is the code that i have problem with. It reads pin codes from text file and it should save them into array with object oriented programming. when I try to display the values in while loop it works fine, but when i try to do it outside while loop, it doesn't work. As for example in the second to last line cout doesn't work.

   #include "branjeDatoteke.h"
    #include "parametri.h"
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <cstring>

    using namespace std;
    void branjeDatoteke() {
    Parametri pin[101];
    string line;
    ifstream myfile("pin.txt");
    if (myfile.is_open())
    {
        for (int i = 0; i <= 100; i++) {
            while (getline(myfile, line))
            {

                pin[i].setPin(line);
                cout << pin[i].readPin() << endl;
                //cout << line << '\n';
            }
        }
        myfile.close();
        cout <<"tole more delat: "<< pin[2].readPin() << endl;
    }

    else cout << "Unable to open file";
}

and this is the CPP file for my Parametri class

#include "parametri.h"
using namespace std;
#include <iostream>

void Parametri::setPin(string pin) {
    this->pinKoda = pin;
}

string Parametri::readPin() {
    return pinKoda;
}

You have a loop inside a loop...

With the first iteration of

for (int i = 0; i <= 100; i++) { ... }

you will read all of the contents of the file because of the inner loop

while (getline(myfile, line))

The second iteration of the outer for loop will not read anything at all, and neither will the next 99 iterations.

That of course means that pin[2] (or indeed pin[1] to pin[100] ) will be initialized. Only pin[0] will be, and it will end up with the last value from the file (because the inner while loop will overwrite it over and over again).


You should change your code to a single loop, perhaps something like this:

for (int i = 0; i <= 100 && getline(myfile, line); i++)
{
    pin[i].setPin(line);
}

Note that this loop might end before you fill in all elements of the pin array. You should probably have a std::vector instead of an array, if there's less (or more.) data in the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM