[英]C : Reading CSV text file with scanf
I am trying to read some values off a CSV file using scanf() for a program I am writing. 我正在尝试使用scanf()从正在编写的程序中读取CSV文件中的一些值。 Here is how I am doing it currently :
这是我目前正在做的事情:
int i, j, id, time1, time2, time3, type, value;
scanf("%d,%d,%d,%d,%d,%d", &id, &time1, &time2, &time3, &type, &value);
printf("%d", value);
For example lets look at this CSV line 5, 14:09:01, 1, 1013
. 例如,让我们看看此CSV行
5, 14:09:01, 1, 1013
。
scanf()
reads in id
and time1
correctly, but after that I am getting some weird values for the other variables. scanf()
正确读取id
和time1
,但是在那之后,我得到了一些其他变量的怪异值。 For example, value
is showing up as 32767
, as well as time2
showing up as 4195536
. 例如,
value
显示为32767
, time2
显示为4195536
。 Does anyone know what I am doing wrong? 有人知道我在做什么错吗?
PS : Is there anyway instead of using time1, time2, and time3 to get the time, I could just print that as a string to avoid those extra variables? PS:无论如何,除了使用time1,time2和time3来获取时间外,我还可以将其打印为字符串以避免那些额外的变量?
File x.csv contains only one line: 文件x.csv仅包含一行:
5, 14:09:01, 1, 1013
This trivial code would do the job for you - time will be read as a string into a char array. 这个简单的代码将为您完成工作-时间将作为字符串读入char数组。 Note that this will read up a comma, so you'll need to get rid of it.
请注意,这将读取逗号,因此您需要摆脱它。
#include <stdio.h>
#include <string.h>
int main(void)
{
int id, type, value;
char time[100];
FILE* f = fopen("x.csv", "r");
fscanf(f, "%d, %s %d, %d", &id, time, &type, &value);
size_t len = strlen(time);
time[len-1] = '\0'; // get rid of comma
printf("%d %s %d %d\n", id, time, type, value);
fclose(f);
return 0;
}
output: 输出:
5 14:09:01 1 1013
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.