C file manipulation (skip lines)

1
Hello, I have a problem with skipping lines in a file, I use fgets (), but it always prints the first line of my file. Home I also did some tests, and for some reason, only one iteration occurs and x enters the if with the value of random. Home Note: Each line of the file is always < 30 characters.

void randInventario() {
    srand(time(NULL));
    int random = rand() % 10;
    nome = new char;
    desc = new char;

    strcpy(parm,"armas.txt");

    FILE* arquivo = fopen(parm,"rt");
    if (arquivo == NULL) {
        cout << "Não foi possível abrir o arquivo." << "\n" << endl;
    }

    int x = 0;
    char text[30];
    while(!feof(arquivo))
    {
      if(x = random)
      {
       fscanf(arquivo, "%s %d %s\n", nome, &dano, desc);
       break;
      }
      fgets(text,30,arquivo);
      ++x;
    }

    fclose(arquivo);
  }
    
asked by anonymous 10.03.2016 / 21:12

1 answer

2
int random = rand() % 10;

random will be 0 , or 1 , or ... 9

  if(x = random)
  {
   fscanf(arquivo, "%s %d %s\n", nome, &dano, desc);
   break;
  }

This if executes whenever random is different from 0 . It also assigns the value of random to x .

Suggestion: Turn on your warnings from your compiler and pay attention to what they say.

replaces the condition of if with a comparison (instead of an attribute)

if (x == random) ...
    
10.03.2016 / 21:49