-1

I have a file with the following contents:

S3 83
S74 2984
S8 12
... and so on for x # of values

The first value tells you which space to store and the second number tells you the content.

For example:

I want to read the file and store "83" in Space 3 of an array. Then store "2984" in Space 74 of the array. Then "12" in space 8 of the array.

How do I read the file and ignore the "S" at the front and store it in that Space in the array with its contents?

Thanks.

  • 3
    See: [How to read and parse input in C — The FAQ](https://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq) – Jonathan Leffler Apr 21 '18 at 21:31
  • 3
    You should probably read lines with [`fgets()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html) or perhaps POSIX [`getline()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html), and then process the lines with [`sscanf()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sscanf.html). Skipping the `S` is trivial; demanding that there is no space between it and the number using `scanf()` et al is harder. – Jonathan Leffler Apr 21 '18 at 21:33
  • 2
    Take the [tour], read [Ask], and [MCVE]. What kind of array are we talking about? Int's, float's, char's? – jwdonahue Apr 21 '18 at 21:38

1 Answers1

0

I came with 2 solution from this :

1-fscanf() : as you can do the following

fscanf(fp, "S%d %d",&slot, &val);

that should do it ,it will skip the 'S' and take the values

2-fgetc() :

simply you can go throw the file with fgetc() and every time you find an 'S' ignore it and start extract data after it

i prefer the first solution , i suggest to read about fscanf() , fgetc()

https://www.tutorialspoint.com/c_standard_library/c_function_fgetc.htm https://www.tutorialspoint.com/c_standard_library/c_function_fscanf.htm

Ashraf
  • 80
  • 1
  • 9
  • 1
    The OP needs some coaching on the difference between "strings", even numerical strings, "12", and integers such as 12. It is not clear to me whether the OP wants to convert to integers or not. – jwdonahue Apr 21 '18 at 22:25
  • me either , but with the limited info. , i assume my answer may help him , otherwise if he provide us with more info. i'll be happy to edit my answer too . – Ashraf Apr 21 '18 at 22:41
  • Yes, 12 is an integer. – c_programming_n00b Apr 22 '18 at 00:26
  • well i think the answer fits your question, u can mark it if you find it useful . – Ashraf Apr 22 '18 at 02:40