用令牌解析字符串的函数

编程入门 行业动态 更新时间:2024-10-28 01:16:16
本文介绍了用令牌解析字符串的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道如何在 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

更多推荐

用令牌解析字符串的函数

本文发布于:2023-10-29 22:44:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1540983.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   字符串   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!