Ghijs Kilani
Ghijs Kilani

Reputation: 166

Read from line with sscanf, including whitespaces, breaking on other character

I'm sorry for the sloppy title, but I didn't know how to format my question correctly. I'm trying to read a .txt, of which every line has information needed to fill a struct. First I use fgets to read the line, and then i was going to use sscanf to read the individual parts. Now here is where I'm stuck: normally sscanf breaks off parts on whitespaces, but I need the whitespace to be included. I know that sscanf allows ignoring whitespaces, but the tricky part is that I then need some other arbitrary character to separate the parts. For example, I have to break the line

Carl Sagan~Contact~scifi~1997

up into parts for Author,Name,Genre,year. You can see I need the space in Carl Sagan, but I need the function to break off the strings on the tilde character. Any help is appreciated

Upvotes: 4

Views: 2567

Answers (3)

mohit
mohit

Reputation: 6064

If your input is delimited by ~ or for instance any specific character: Use this:

sscanf(s, "%[^~]", name);

[^ is conversion type, that matches all characters except the ones listed, ending with ]

Here is the sample program for testing it:

#include <stdio.h>

int main(int argv, char **argc)
{
    char *s = "Carl Sagan~Contact~scifi~1997";
    char name[100], contact[100], genre[100];
    int yr;

    sscanf(s, "%99[^~]~%99[^~]~%99[^~]~%d", name, contact, genre, &yr);
    printf("%s\n%s\n%s\n%d\n", name, contact, genre, yr);

    return 0;
}

Upvotes: 4

P0W
P0W

Reputation: 47824

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

char* mystrsep(char** input, const char* delim)
{
  char* result = *input;
  char* p;

  p = (result != NULL) ? strpbrk(result, delim) : NULL;

  if (p == NULL)
    *input = NULL;
  else
  {
    *p = '\0';
    *input = p + 1;
  }

  return result;
}

int main()
{
  char str[] = "Carl Sagan~Contact~scifi~1997";
  const char delimiters[] = "~";
  char* ptr;
  char* token;

    ptr = str;
  token = mystrsep(&ptr, delimiters);
  while(token)
    {
      printf("%s\n",token);
       token = mystrsep(&ptr, delimiters);
    }   
  return 0;
}

Output :-

Carl Sagan
Contact
scifi
1997

Upvotes: 0

pattivacek
pattivacek

Reputation: 5823

You need strtok. Use ~ as your delimiter.

See the documentation: http://linux.die.net/man/3/strtok

strtok has some drawbacks but it sounds like it will work for you.

EDIT:

After reading this, it sounds like you can use sscanf cleverly to achieve the same result, and it may actually be safer after all.

Upvotes: 0

Related Questions