在C中使用指向行令牌的指针时出现的问题 [英] Issue when using pointer to line tokens in C

查看:124
本文介绍了在C中使用指向行令牌的指针时出现的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个程序,该程序需要读取包含银行帐户和交易历史记录的CSV文件.要访问某些信息,我有一个函数getfield,它逐个令牌地读取每个行令牌:

I have created a program that requires reading a CSV file that contains bank accounts and transaction history. To access certain information, I have a function getfield which reads each line token by token:

const char* getfield(char* line, int num)
{
    const char *tok;
    for (tok = strtok(line, ",");
            tok && *tok;
            tok = strtok(NULL, ",\n"))
    {
        if (!--num)
            return tok;
    }
    return NULL;
}

稍后我将在代码中使用它来访问帐号(在位置2)和交易金额(在位置4):

I use this later on in my code to access the account number (at position 2) and the transaction amount(position 4):

...
while (fgets(line, 1024, fp))
{


        char* tmp = strdup(line); 

        //check if account number already exists

        char *acc = (char*) getfield(tmp, 2); 
        char *txAmount = (char*)getfield(tmp, 4);

        printf("%s\n", txAmount);
        //int n =1;
        if (acc!=NULL && atoi(acc)== accNum && txAmount !=NULL){
                if(n<fileSize)
                {
                        total[n]= (total[n-1]+atof(txAmount));
                        printf("%f", total[n]);
                        n++;

                }

         }
         free(tmp1); free(tmp2);
}
...

char *acc = (char*) getfield(tmp, 2)似乎没有问题,但是当我将getfield用作char *txAmount = (char*)getfield(tmp, 4)时,下面的打印语句向我显示我始终拥有NULL.对于上下文,文件当前读取为(第一行为空):

No issue seems to arise with char *acc = (char*) getfield(tmp, 2), but when I use getfield for char *txAmount = (char*)getfield(tmp, 4) the print statement that follows shows me that I always have NULL. For context, the file currently reads as (first line is empty):


AC,1024,John Doe
TX,1024,2020-02-12,334.519989
TX,1024,2020-02-12,334.519989
TX,1024,2020-02-12,334.519989

我以前曾问过是否需要在我的代码的单独部分中使用free(acc)(

I had previously asked if it was required to use free(acc) in a separate part of my code (Free() pointer error while casting from const char*) and the answer seemed to be no, but I'm hoping this question gives better context. Is this a problem with not freeing up txAmount? Any help is greatly appreciated !

(此外,如果有人对标题有更好的建议,请让我知道如何措辞更好,我是堆栈溢出的新手)

(Also, if anyone has a better suggestion for the title, please let me know how I could have better worded it, I'm pretty new to stack overflow)

推荐答案

问题是strtok用'\0'替换了找到的定界符.您需要获取该行的新副本.
或使用getfield (NULL, 2)从上次停止的地方继续.

The issue is that strtok replaces the found delimiters with '\0'. You'll need to get a fresh copy of the line.
Or continue where you left off, using getfield (NULL, 2).

这篇关于在C中使用指向行令牌的指针时出现的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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