-2

I have a textfile of numbers written in words, with spaces between like..

zero three five two one .. etc there are 3018 words in total.

This is my code:

#include <stdio.h>

int main(void)
{
    int i = 0;
    int d = 0;
    int j = 0;
    char array[9054][5];
    char hi[9054];

    FILE *in_file;

    in_file = fopen("message.txt", "r");

    while (!feof(in_file))
    {
        fscanf(in_file, "%s", array[i]); 
        i++;
    }
    printf(array[9049]);
    while (1);
        return 0;

}

so the 9049th worth in my textfile is the number three.. but when I run this script, it prints "threethreezero"instead?? i thought the fscanf ignored whitespace (spaces) so why does accept another three and zero into this string?

domdomcodecode
  • 2,355
  • 4
  • 19
  • 27
anony
  • 79
  • 1
  • 2
  • 10
  • 3
    C string `"three"` does not fit in a 5 `char` array. – chux - Reinstate Monica Dec 03 '15 at 23:20
  • 2
    This is certainly not a script. If you don't know the difference between a script and a compiled program you should learn about it. Also [`while (!feof(in_file))` is alwasy wrong](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – Iharob Al Asimi Dec 03 '15 at 23:21
  • In addition to the two comments that are already correct `printf(array[9049]);` Learn how to use `printf`. Also why the `while(1)` loop at the end? Why not just `return 0` – TheQAGuy Dec 03 '15 at 23:24
  • oh yeah so it should all be fine if i change 5 to 6, and yea im beginner to programming i use words senselessly – anony Dec 03 '15 at 23:24
  • @anony, it could be fine. It depends on the content of your file, and your program shall not depend on that because then it will work just for that file and there is no point in writing such a program. – Iharob Al Asimi Dec 03 '15 at 23:25

1 Answers1

1

OP figured things out with the help of comments, so here is a cumulative fix.

#include <stdio.h>

int main(void)
{
    int i = 0;
    int d = 0;
    int j = 0;
    // Make room for the null character
    char array[9054][5+1];
    char hi[9054];

    FILE *in_file;

    in_file = fopen("message.txt", "r");

    //check `fscanf()`'s return value rather than using feof()
    // Limit input put with 5
    while (fscanf(in_file, "%5s", array[i]) == 1); 
        i++;
    }
    // Check that code read enough input
    if (i >= 9049) {
      // Do not use `printf()` on uncontrolled strings that may contain %
      fputs(array[9049], stdout);
    } else {
      puts("Oops");
    }

    while (1);
    return 0;
}
Quentin
  • 62,093
  • 7
  • 131
  • 191
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256