C file manipulation (skip lines)

Asked

Viewed 3,898 times

1

Hello, I’m having a problem to skip lines in a file, I use fgets(), but it always prints the first line of my file.
I also did some tests, and for some reason, there is only one iteration and x enters the if with the value of Random.
Note: each line in 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);
  }
  • Since you are using C++, do not use fgets, fscanf, fopen, etc. Using streams can already be a big step to facilitate the work.

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 the warnings of your compiler and watch what they say.

replaces the condition of if by a comparison (instead of an assignment)

if (x == random) ...
  • Wow, sheer inattention. I ended up turning off the warnings for other reasons and ended up with an even bigger problem. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.