There are a number of problems with the above code. The warning about the use of NULL is straightforward to fix, use 0 instead, since the values are integers and 0 agrees with the initial values assigned at the start.
But there are other problems. Sometimes the loop uses 1708
|
for(int i=0; i<1708; i++){
|
and other times it uses 1709
|
for(int i=0; i<1709; i++){
|
The value of 1709 is an error, it will attempt to access an array element which is beyond the array boundary. C and C++ will allow this kind of error with no warning or error message. One way to reduce problems is to use a defined constant, set it once at the start and use it consistently throughout.
Other problems. Non-standard variable-length arrays:
|
char tmp[contador_auxiliar];
|
which is not legal in ISO standard C++
Also the code is too complex for a fairly simple task of reading a pair of integers.
Also. Do not loop on eof(). This is almost always wrong and can give unexpected results.
Simplified code, assuming the file is well-formed with just two values per line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <iostream>
#include <fstream>
using namespace std;
const int SIZE = 1709; // we know the largest userid is less than 1709
int main()
{
int usuarios[SIZE] = { 0 }; // array structure of SIZE users
int sesiones[SIZE] = { 0 }; // every user starts with 0 minutes and 0 sessions
ifstream fi("tiempoespacios.txt"); // read archive tiempo.txt
int id_usuario;
int duracion_usuario;
while ( fi >> id_usuario >> duracion_usuario )
{
usuarios[id_usuario] = usuarios[id_usuario] + duracion_usuario;
sesiones[id_usuario] = sesiones[id_usuario] + 1;
}
// find user with most sessions
int user_sesiones = 0;
int user_sesiones_i = 0;
for (int i=0; i<SIZE; i++)
{
if (sesiones[i] > user_sesiones)
{
user_sesiones = sesiones[i];
user_sesiones_i = i;
}
}
cout<<"El usuario con mayor cantidad de sesiones es: " << user_sesiones_i << endl;
}
|
Note:
SIZE = 1709
. This allows an array with subscripts in the range 0 to 1708 inclusive.