解析用逗号分隔字符串的作品只有一次? [英] Parsing a string separated by commas works only once?

查看:109
本文介绍了解析用逗号分隔字符串的作品只有一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,当我preSS菜单'A'我做了以下code,它解析用逗号分隔的数字。我第一次preSS'A'的结果是100%准确。但第二次+我preSS'A'从菜单中重复同样的code,我得到奇怪的结果。我使用的MPLAB C18编译器与PIC18

I have a menu when I press 'A' I do the following code which parses the numbers separated by commas. The first time I press 'A' The results are 100% accurate. But the second+ times I press 'A' from the menu to repeat the same code, I get strange results. I am using MPLAB C18 Compiler with PIC18

我使用MPLAB C18 C编译器,PIC18

I am using MPLAB C18 Compiler with PIC18

第一时间输出

0002

0100

0200

0100

二+时报输出

0002

code

char somestr[] ="2,0100,0200,0100";
char *pt;
int a;
pt = strtokpgmram (somestr,",");

while (pt != NULL) 
{
    a = atoi(pt);
    printf("%d\n", a);
    pt = strtokpgmram (NULL, ",");
}

你怎么解决它,这样我每次preSS'A'从菜单中时,我得到了相同的结果作为首次输出?

How do you fix it so that every time I press 'A' from the menu I get the same results as first time output?

感谢您!

推荐答案

这是因为,调用的strtok()将改变原有的字符串本身。你有打电话的strtok()之前,使原始字符串的副本。

This is because, calling strtok() will change the original string itself. You have to make a copy of the original string before calling strtok().

我做了一个示例程序,尤其是对你的理解。

I made a sample program especially for your understanding.

你看,它的记号化功能,每次我提出一个副本,并使用该副本。

See, it in the tokenize function, everytime I am making an copy and using the copy.

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

void tokenize(char* s){

    char *pt;
    int a;

    char* copy_somestr = malloc((strlen(s)+1) * sizeof(char));
    strcpy(copy_somestr,s);

    pt = strtok (copy_somestr,",");

    while (pt != NULL)
    {
        a = atoi(pt);
        printf("a = %d somestr = %s\n", a,s);
        pt = strtok (NULL, ",");
    }

    free(copy_somestr);
}
void main(){
    char somestr[] ="2,0100,0200,0100";

     /*
    printf("Beginning somestr = %s",somestr);
    // If you tokenize here without making any copy using somestr, It still works well But after this call somestr will become unusable.
    printf("Afterlast somestr = %s",somestr);
    */


    tokenize(somestr);

     // You could still use somestr
    printf("I could still use somestr = %s\n",somestr);


    tokenize(somestr);  

}

这篇关于解析用逗号分隔字符串的作品只有一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆