Faisal Al-shawi
Faisal Al-shawi

Reputation: 111

sscanf until it reaches a comma

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 :)

Upvotes: 10

Views: 33098

Answers (4)

Bhaumik Mistry
Bhaumik Mistry

Reputation: 99

Assuming the format of the text file is constant you can use the following solution.

std::ifstream ifs("datacar.txt");
    if(ifs)
    {
       std::string line;
       while(std::getline(ifs,line))
       {
            /* optional to check number of items in a line*/
            std::vector<std::string> row;
            std::istringstream iss(line);
            std::copy(
                std::istream_iterator<std::string>(iss),
                std::istream_iterator<std::string>(),
                std::back_inserter(row)
            );

            /*To avoid parsing the first line and avoid any error in text file */
            if(row.size()<=2)
                continue;


            std::string format = "%s %s %s %f %[^,] %d";
            char year[line.size()],make[line.size()],three[line.size()],full[line.size()];
            float numberf;
            int numberi;  

            std::sscanf(line.c_str(),format.c_str(),&year,&make,&three,&numberf,&full,&numberi);

        /* create your object and parse the next line*/


        }

    }

Upvotes: -1

MOHAMED
MOHAMED

Reputation: 43528

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);

Upvotes: 22

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158479

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;
}

Upvotes: 1

K Scott Piel
K Scott Piel

Reputation: 4380

See the documentation for strtok and/or strtok_r

Upvotes: -2

Related Questions