CSV 到 C 中的数组
我正在尝试将 CSV 文件加载到单个维度数组中。我可以输出 CSV 文件的内容,但在尝试将其复制到数组中时遇到了一些麻烦。
这是我现有的代码,我意识到它可能非常糟糕,但我正在自学:
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024
#define MAX_CSV_ELEMENTS 1000000
int main(int argc, char *argv[])
{
char line[MAX_LINE_LENGTH] = {0};
int varCount = 0;
char CSVArray[MAX_CSV_ELEMENTS] = {0};
FILE *csvFile = fopen("data.csv", "r");
if (csvFile)
{
char *token = 0;
while (fgets(line, MAX_LINE_LENGTH, csvFile))
{
token = strtok(&line[0], ",");
while (token)
{
varCount++;
CSVArray[varCount] = *token; //This is where it all goes wrong
token = strtok(NULL, ",");
}
}
fclose(csvFile);
}
return 0;
}
我应该有更好的方法吗?提前致谢!
I'm trying to load a CSV file into a single dimentional array. I can output the contents of the CSV file, but in trying to copy it into an array I'm having a bit of trouble.
Here is my existing code, which I realise is probably pretty bad but I'm teaching myself:
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024
#define MAX_CSV_ELEMENTS 1000000
int main(int argc, char *argv[])
{
char line[MAX_LINE_LENGTH] = {0};
int varCount = 0;
char CSVArray[MAX_CSV_ELEMENTS] = {0};
FILE *csvFile = fopen("data.csv", "r");
if (csvFile)
{
char *token = 0;
while (fgets(line, MAX_LINE_LENGTH, csvFile))
{
token = strtok(&line[0], ",");
while (token)
{
varCount++;
CSVArray[varCount] = *token; //This is where it all goes wrong
token = strtok(NULL, ",");
}
}
fclose(csvFile);
}
return 0;
}
Is there a better way I should be doing this? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
*token
表示取消引用指针token
,该指针是strtok
找到的字符串中第一个字符的地址。这就是您的代码仅使用每个标记的第一个字符填充CSVArray
的原因。您应该有一个 char 指针数组来指向标记,例如:
然后为其元素分配一个指针:
或者,您可以每次复制整个标记:
*token
means dereferencing the pointertoken
which is the address of the first character in a string thatstrtok
found. That's why your code fillsCSVArray
with just the first characters of each token.You should rather have an array of char pointers to point at the tokens, like:
And then assign a pointer to its elements:
Alternatively, you can copy the whole token each time:
你对问题线的看法是正确的。这是因为您正在分配一个指针,而不是复制文本。
尝试在这里 http://boredzo.org/pointers/ 有关指针的教程。
You are right about the problem line. It is because you are assigning a pointer, not copying the text.
Try here http://boredzo.org/pointers/ for a tutorial on pointers.
看起来您正在尝试将从
strtok
返回的char *
放入char
数组中。我认为您想将 CSVArray 声明为:
It looks like you're trying to put the
char *
that comes back fromstrtok
into thechar
array.I think you want to declare
CSVArray
as: