-2

I am developing a program in which I have to read a text file and store the integer values in an array from the text file. I have searched for how to do and found this method. But the result is not as expected.

For instance, say, I have integer values in a text file called 'integers.txt' such as 1,2,3,4,5,6,7,8,9,10. I am reading those values and add it one by one with the new array called 'myarray'. But after performing an addition, using while loop, I have got only zero as output in 'myarray'

Here is my code:

int main(int argc, char **argv) 
{
  int myArray[2048]={0};
  int value;
  int i = 0;
  while(file >> value && i<sizeof(myArray))
 { 
   myArray[i] += value;
   i++;
   std::cout<<myArray[i]<<std::endl;
   std::cout<<value<<std::endl;
 }  

 std::cout<<i<<std::endl;

 std::cout<< sizeof(myArray)<<std::endl;
 return 0;
}

Thanks for the help!

CNA
  • 121
  • 7

4 Answers4

2

i is incremented too early. Do it after the printing.

while(file >> value && i<sizeof(myArray))
{ 
   myArray[i] += value;
   std::cout<<myArray[i]<<std::endl;
   std::cout<<value<<std::endl;

   i++; // ~~~~ Do it after the printing.
}
2

You are incrementing i before printing the value and initially all array elements are initialised to 0.

So when we reach at the last integer of file, it stores it and increments i to a value which is out-of-bounds. Increment i after the print statements

acraig5075
  • 10,588
  • 3
  • 31
  • 50
Abhishek Keshri
  • 3,074
  • 14
  • 31
0

I believe the output differs from what you expect because you try to add value to a slot of array which is not set. Try changing:

myArray[i] += value;

To:

myArray[i] = value;
thebluef0x
  • 23
  • 4
0
   myArray[i] += value;
   i++;
   std::cout<<myArray[i]<<std::endl;

You assign a value to myArray[i], then you increment i before using it to print myArray[i], so you end up printing the next value in myArray rather than the one you just modified.

Swapping the two last lines takes care of that:

   myArray[i] += value;
   std::cout<<myArray[i]<<std::endl;
   i++;

Also note that if your file contains more than 2048 numbers, you will access memory outside myarray and your program is likely to crash. So instead of this:

while(file >> value && i<sizeof(myArray))

do something like this:

while(file >> value && i < sizeof(myArray) / sizeof(myArray[0]))
Sid S
  • 6,037
  • 2
  • 18
  • 24