c - Issue when using pointer to line tokens in C
问题描述
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;
}
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);
}
...
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
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)
.
推荐阅读
- php - Symfony4 部署到共享主机得到错误 500
- python - MobilenetSSDv2 冻结迁移学习
- javascript - 鼠标向上事件在 SVG 中无法正常工作
- vb.net - 从 Webrequest 字符串中提取信息的最佳方法
- python - 如何在 Jupyter Notebooks 中使用 Pylint 或其他 linter?
- c - 如何找到第n个数字?
- javascript - 如何使用选择选项更改 DataTable 中的数据
- css - 版本 77 更新后 Chrome 浏览器更改样式
- java - Android Java:当对话框关闭时,如何防止我的对话框短暂显示 MainActivity 应用程序名称?
- ubuntu - tpm2-tools seal-unseal 重启后数据