0

So i have a while loop to read comments off a text file as follows. There could be things after the comments so that shouldn't be ruled out. Here is my code as follows:

int i = 0;
while(!feof(fd) || i < 100) {
    fscanf(fd, "#%s\n", myFile->comments[i]);
    printf("#%s\n", myFile->comments[i]);
    getch();
    i++;
}

Comment format:

# This is a comment
# This is another comment

Any idea why it only returns the first character?

EDIT:

Here is my comments array:

char comments [256][100];
madcrazydrumma
  • 1,847
  • 3
  • 20
  • 38

3 Answers3

1

The comments array allows for 256 strings of up to 100 characters each.
The scanset " %99[^\n]" will skip leading whitespace and scan up to 99 (to allow for a terminating '\0') characters or to a newline whichever comes first.
The if condition will print the line and increment i on a commented line.

int i = 0;
char comments[256][100];
while( i < 256 && ( fscanf(fd, " %99[^\n]", comments[i]) == 1)) {
    if ( comments[i][0] == '#') {
        printf("%s\n", comments[i]);
        i++;
    }
}
user3121023
  • 8,181
  • 5
  • 18
  • 16
0

Because scanf with %s reads until ' ' or '\n' or EOF. Use something like fgets.

V. Kravchenko
  • 1,859
  • 10
  • 12
0

"%s" does not save spaces.

It reads and discards leading white-space and then saves non-white-space into myFile->comments[i]

// reads "# This ", saving "This" into myFile->comments[i]
fscanf(fd, "#%s\n", myFile->comments[i]);
// Prints "This"
printf("#%s\n", myFile->comments[i]);
// reads and tosses "i"
getch();

// next fails to read "s a comment" as it does not begin with `#`
// nothing saved in myFile->comments[i]
fscanf(fd, "#%s\n", myFile->comments[i]);
// output undefined.
printf("#%s\n", myFile->comments[i]);

Instead, avoid scanf(). To read a line of input use fgets()

char buf[100];
while (fgets(buf, sizeof buf, stdin)) {
  if (buf[0] == '#') printf("Comment %s", &buf[1]);
  else printf("Not comment %s", buf);
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256