用令牌解析字符串的函数 [英] Function to parse string with tokens
问题描述
我知道如何在 C# 和 VB 中编程,但不知道如何使用 C++,并且必须为使用 C++ 的条码扫描器编写一个小 exe :(
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++ :(
此时,我尝试解析具有多个以/"分隔的数据的扫描条码,我发现存在一个 strtok 函数,手动"对其进行了测试并且工作正常,但我还没有实现一个可以调用的工作函数正确,我现在拥有的:
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!
}
}
如果我在没有函数getElemStr"的情况下使用 strtok 它可以正常工作,但我也尝试在其他地方使用它.
if I use strtok witout a function "getElemStr" it work ok but I try to use it on other places too.
我可以这样使用 strtok 吗?你有一个工作例子吗?pd:我不知道指针(抱歉),了解这个的好文档?
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?
推荐答案
这是一个不使用 boost 的 C++ 解决方案.
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;
}
输出:
710015733801Z
1
35
这篇关于用令牌解析字符串的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!