sscanf until it reaches a comma

26,146

Solution 1

If the order of your variables in the string is fixe, I mean It's always:

string, string, string, int, float

the use the following format specifier in sscanf():

int len = strlen(str);
char a[len];
char b[len];
char c[len];
unsigned long d;
float e;

sscanf(" %[^,] , %[^,] , %[^,] , %lu , %lf", a, b, c, &d, &e);

Solution 2

This example using strtok should be helpful:

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

int main ()
{
  char str[] ="hello, world, I, 287876, 6.0" ;
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str,",");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, ",");
  }
  return 0;
}
Share:
26,146
Faisal Al-shawi
Author by

Faisal Al-shawi

Updated on July 30, 2022

Comments

  • Faisal Al-shawi
    Faisal Al-shawi almost 2 years

    I'm trying to scanf words and numbers from a string looks like: "hello, world, I, 287876, 6.0" <-- this string is stored in a char array (string) What I need to do is to split things up and assign them to different variables so it would be like

         char a = "hello"
         char b = "world"
         char c = "I"
         unsigned long d = 287876
         float e = 6.0
    

    I know that regular scanf stops reading from stdin when it reaches a white space. So I've been thinking that there might be a way to make sscanf stop reading when it reaches a "," (comma)

    I've been exploring the library to find a format for sscanf to read only alphabet and numbers. I couldn't find such a thing, maybe I should look once more.

    Any help? Thanks in advance :)

  • K Scott Piel
    K Scott Piel about 11 years
    I'm not sure if it is or it isn't -- hence the "AND/OR" in my response. IF the strtok_r flavor is supported, it is thread safe and recursion safe, not a global state function as is strtok -- either way... one variant of strtok or another is a solution to the problem.
  • K Scott Piel
    K Scott Piel about 11 years
    For the record... strtok_r is POSIX.1-2001
  • Faisal Al-shawi
    Faisal Al-shawi about 11 years
    Yes, that's what I'm doing. Thanks
  • user2284570
    user2284570 almost 9 years
    @MOHAMED : How I can do it for scanning until it match a particular substring?
  • chqrlie
    chqrlie almost 5 years
    For safety, the arrays should be defined with a length of len + 1, since e is a float, the last format should be %f and some of the spaces in the format string are redundant: " %[^,], %[^,], %[^,],%lu,%f"