0

Here is the format of the file that is being read:

type                                            Extensions

application/mathematica          nb ma mb
application/mp21                      m21 mp21

I am able to read each entry from the file. Now I want to make a key-value pair where the output for the above entries would be like
{nb: application/mathematica}
{ma:application/mathematica}

and so on.

this is my current code to simply read through the entries

 char buf[MAXBUF];
 while (fgets(buf, sizeof buf, ptr) != NULL)
    {
        if(buf[0] == '#' || buf[0] == '\n')
            continue;  // skip the rest of the loop and continue



        printf("%s\n", buf);
}
sana
  • 763
  • 9
  • 19
  • 1
    What is the problem preventing coding? – chux - Reinstate Monica Dec 09 '19 at 04:02
  • Does this answer your question? [store known key/value pairs in c](https://stackoverflow.com/questions/14731939/store-known-key-value-pairs-in-c) – Achal Dec 09 '19 at 04:10
  • 2
    If you're using `strtok()` (or, better, `strtok_r()` on POSIX or `strtok_s()` on Windows), or if you're using `sscanf()` (see [Using `sscanf() in a loop](https://stackoverflow.com/questions/3975236/how-to-use-sscanf-in-loops) for useful information), then both of those skip over multiple blanks as happily as single blanks. Skipping comment and blank lines like you are is often a good idea — well done. Time to make an honest attempt at the splitting part of the process. – Jonathan Leffler Dec 09 '19 at 06:04

1 Answers1

1

"How to split the a string into separate words in C, where the space is not constant?"

A simple answer would be using strtok() (string.h library), but keep it mind that this function affects your initial string. So, if you want to use it again, you should use an temporary variable equal to your initial string.

char *p = strtok(char *str, const char *delim)

where, in place of delim you should place : " ".

Basically, strtok splits your string according to given delimiters.

Here, i let u an example of strtok:

char* p = strtok(str," ");
while(p != NULL){
   printf("%s\n",p);
   p=strtok(NULL," ");
}
darksz
  • 115
  • 2
  • 12