0

I'm new to c++ programming and i tried to use struct arrays ( dunno if I say it in the way you understand ). Program does read the variables from the text file but it reads it for 2 times, prob It's not a huge problem as the variables are not changed but just in case

struct menesine_temperatura
{
    int diena[10];
    int rytas[10];
    int pietus[10];
    int vakaras[10];
};


int main()
{
    menesine_temperatura mt;
    int n;
    ifstream failas("duomenys.txt");

    while(!failas.eof())
    {
        failas >> n;
        cout << n << endl;

        for(int i = 0; i < n; i++)
        {
            failas >> mt.diena[i] >> mt.rytas[i] >> mt.pietus[i] >> mt.vakaras[i];
            cout << mt.diena[i] << mt.rytas[i] << mt.pietus[i] << mt.vakaras[i] << endl;
        }

    }

    failas.close();

    return 0;
}

as I have mentioned before I' new to this stuff, so help would be appreciated.

haribo
  • 25
  • 5

1 Answers1

0

With the code you have you, it will appear as if the last set of numbers are being read twice.

Here's a simple example that explains the logic error.

int main()
{
   int n; 
   std::ifstream inf("data.txt");
   while ( !inf.eof() )
   {
      inf >> n;
      std::cout << n << std::endl;
   }
}

and your input file consists of

10
20

In the first iteration of the loop, 10 is read into n and 10 is printed. In the second iteration of the loop, 20 is read into n and 20 is printed.

At this point inf.eof() is still false. So you enter the loop the third time. At this time, nothing is read into n but the value of n still 20 and 20 is printed.

The logic error is that just because inf.eof() is false, you assume that there is still some data in the file that can be read.

A better way would be to use:

int main()
{
   int n; 
   std::ifstream inf("data.txt");
   while ( inf )
   {
      if ( inf >> n )
      {
         std::cout << n << std::endl;
      }
   }
}

I hope this gives you enough information on how to update your program.

R Sahu
  • 196,807
  • 13
  • 136
  • 247