1

I am trying to read an external text file. The file contains both numbers and words in the form:

hello 1239 4943 melissa

(with each element on its own line) The actual text file has over 1200 words. I want to read each line and store them as strings, but fscanf skips over the numbers. How can I read the numbers into my program and store them as strings?

    char word[1263][13];
    FILE * fh;

    fh=fopen("wordlist.txt","r");
    for (a=0;a<1263;a++)
    {
      fscanf(fh,"%s",word[a]);
    }
    fclose(fh);
Free_D
  • 11
  • 1
  • 3
  • Please post the bit of code that does the reading so that we can see what is going wrong. – Dipstick May 14 '11 at 07:34
  • 1
    In general, `scanf` and `fscanf` have their share of problems. I recommend using `fgets` to read the data line-by-line, then using `sscanf` if you need the formatting. – Chris Lutz May 14 '11 at 08:33
  • I tried fgets, but it still seems to skip the numbers, as well as reading the newline character into the sting which messed up my later code. – Free_D May 16 '11 at 06:52

2 Answers2

1

You should be able to achieve this via fscanf

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( int argc, char ** argv ) {
   FILE * source_file;

   char * buffer = malloc( 100 * sizeof(char));     
   char ret = '\0';

   source_file = fopen("TENLINES.TXT","r+");
   do {
      ret = fscanf(source_file, "%s", buffer);
      printf("%s\n", buffer);

   } while (ret != EOF);

   return 0;
}
zellio
  • 31,308
  • 1
  • 42
  • 61
0

How are you using fscanf? The following code will work:

char s1[100];
int i1;
int i2;
char s2[100];

while (!feof (file))
  {
    // Should check return value.
    fscanf (file, "%s %d %d %s", s1, &i1, &i2, s2);
    printf ("%s %d %d %s\n", s1, i1, i2, s2);
  }
Vijay Mathew
  • 26,737
  • 4
  • 62
  • 93