开发者

Function to parse string with tokens

I know how to program in C# and VB but not have idea about how to use C++ and have to program a little exe to a barcode scanner that use C++ :(

In this moment I try to parse a scanned barcode that have multiple data sepparated with a "/", I find that exist a strtok function, tested it "manually" and worked ok but I not implemented yet a working function to call it correctly, what I have now:

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

int elemStr(char *str, char sep)
{
   int cantElem;
   unsigned ich;

   cantElem = 0;

   if (strlen(str) > 0) //at least 1 elem
      cantElem++;

   for (ich = 0; ich < strlen(str); ich++)
   {         
      if (str[ich] == sep)
         cantElem++;      
   }                
   return cantElem;
}

char* getElemStr(char *str, char sep[], int elem)
{   
    char *tempStr = NULL;
    char *tok;                   
    int currElem = 1;

    // 1st data
    strcpy( 开发者_运维知识库tempStr, str);
    tok = strtok( tempStr, sep);

    while( currElem != elem )
    {       
        // Get next tokens:
        tok = strtok( NULL, sep );
        currElem++;
    }

    return tok;
}


void main( void )
{
    char barcode[] = "710015733801Z/1/35";

    char sep[] = "/";
    char sep1 = sep[0];

    char barcd[20];
    char piezaChar[4];
    int pieza;
    char mtsChar[4];

    int cantElem;

    cantElem = elemStr(barcode, sep1 );

    if (cantElem >= 1)
    {
        strcpy(barcd, getElemStr(barcode,sep,1) ); //pasa a str resultado;
        printf("Cod: %s\n", barcd ); //STACK OVERFLOW HERE!
    }
 }

if I use strtok witout a function "getElemStr" it work ok but I try to use it on other places too.

Can I use strtok like this? You have a working example? pd: I not have idea about pointers (sorry), good doc to learn about that?


Since you specifically asked about C++, I'm going to ignore your very c-style code and show you how to do this in C++:

#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::string barcode = "710015733801Z/1/35";

    std::string sep = "/";
    std::vector<std::string> v;
    boost::split(v, barcode, boost::is_any_of(sep));

    for(size_t i=0; i<v.size(); ++i)
        std::cout << v[i] << '\n';
}


strtok destroys your original string. So i don't think it can be used with a char* that points to a static string. Static strings get copied to a read only portion of the executable.


Here is a C++ solution that doesn't use boost.

#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::string barcode = "710015733801Z/1/35";

    std::stringstream ss(barcode);
    std::string elem;

    while(std::getline(ss, elem, '/'))
    {
        //do something else meaningful with elem
        std::cout << elem << std::endl;
    }

    return 0;
}

Output:

710015733801Z
1
35
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜