tags:

views:

186

answers:

2

I have a file where each line consists of some words and a number. I'd like to read the file, one line at a time, displaying just the words. Then the program should wait for a key press, and display the number on a certain key, and go on to the next line without displaying the number in the default case. My problem is, the only solution I came up with displays the next line with a number, not the current one. Here's the faulty code;

  FILE *file = fopen("randwords", "r");
  if(file)
  {
    char line[64];
    while(fgets(line, sizeof line, file))
    {
      ch = getch();
      clear();
      if(ch == 'q') break;
      if(ch == 'z') s = 1;
      move(LINES/2, (COLS - 20)/2);
      for(i=0; i < strlen(line); i++)
      {
        if(!s && line[i] >= '0' && line[i] <= '9') break;
        addch(line[i]);
      }
      s = 0;
    }
    fclose(file);
    system("rm randwords");
  }
+2  A: 

use ftell() and fseek() to allow you to reread a line. You will need a variable to hold the previous file position.

Joshua
+1  A: 

This is what you're doing:

read line
wait for key
print *full* line if key was 'z'
    or print words only otherwise

Note that you are waiting for key with no line displaying on the first time through the loop, or, as you say, with the line from the last pass through the loop.

This is what you should be doing:

read line
print words only
wait for key
if key was 'z'
    print rest of line
pmg