我不熟悉C.我必须使用函数从.csv文件中读取三个不同数组的值。函数原型如下所示:
void readUsageFromFile(double usage1[], double usage2[], double usage3[]);
.csv文件采用以下格式:
Day,Time,Apartment1,Apartment2,Apartment3
01,00:00,0,0.001,0
01,01:00,0,0,0
01,02:00,0,0,0
...
第一个值是日,第二个值是一天中的时间,第三个值是第一个公寓的用水量,第四个值是第二个公寓,第五个是第三个公寓。这些值代表每个公寓每天每小时30天的用水量,因此有720行值
所有这些值都在一列中,共有721行,包括标题日,时间,公寓1,......
我还获得了一个可用于处理.csv文件的函数,但它只会让我感到困惑。这是功能:
#define DEBUG 0
void csvToStrings(char *csvString, char *day, char *time, char *usage1, char
*usage2, char *usage3)
{
// Declare variables
int i, j;
char c;
if (DEBUG)
printf("csvToStrings: Length of string is %d\n", strlen(csvString));
// Read day
i = 0;
j = 0;
c = csvString[i++];
while (c != ',')
{
day[j++] = c;
c = csvString[i++];
}
day[j++] = '\0';
if (DEBUG)
printf("csvToStrings: day string: %s\n", day);
// Read time
j = 0;
c = csvString[i++];
while (c != ',')
{
time[j++] = c;
c = csvString[i++];
}
time[j++] = '\0';
if (DEBUG)
printf("csvToStrings: time string: %s\n", time);
// Read usage1
j = 0;
c = csvString[i++];
while (c != ',')
{
usage1[j++] = c;
c = csvString[i++];
}
usage1[j++] = '\0';
if (DEBUG)
printf("csvToStrings: usage1 string: %s\n", usage1);
// Read usage2
j = 0;
c = csvString[i++];
while (c != ',')
{
usage2[j++] = c;
c = csvString[i++];
}
usage2[j++] = '\0';
if (DEBUG)
printf("csvToStrings: usage2 string: %s\n", usage2);
// Read usage3
j = 0;
c = csvString[i++];
while (c != '\0')
{
usage3[j++] = c;
c = csvString[i++];
}
usage3[j++] = '\0';
if (DEBUG)
printf("csvToStrings: usage3 string: %s\n", usage3);
}
想法是在函数 readUsageFromFile 中使用函数 csvToString()。我已经看到了如何读取.csv文件中的值的示例,但我对如何将值读入不同的数组并将其分配给正确的数组感到困惑。我怎样才能开始这个?
答案 0 :(得分:0)
我不打算为你解决问题。但是我要做的是编写csvToStrings
函数的人应该首先做的事情:我将正确记录函数:
/*
* Function to parse a csv line
*
* The function reads the csv line from `csvString` parameter
* and writes the values to the `day`, `time`, `usage1`, `usage2` and `usage3` parameters
*
*
* Parameters:
* csvString - C string. Input. Mandatory
* a CSV line. A comma (,) separated list of values
* respecting the format:
* Day,Time,Apartment1,Apartment2,Apartment3
*
* day - string buffer. output. Mandatory
* a preallocated buffer to write the parsed day value to.
* the buffer must have a size to fit
* the value including the null terminating character
*
* time - string buffer. output. Mandatory
* a preallocated buffer to write the parsed time value to.
* the buffer must have a size to fit
* the value including the null terminating character
*
* usage1-3 - string buffer. output. Mandatory
* 3 preallocated buffers to write the parsed usage1-3 values to.
* the buffers must have a size to fit
* the values including the null terminating character
*
*
*/
void csvToStrings(char *csvString, char *day, char *time, char *usage1,
char *usage2, char *usage3);
另外,该功能有几个问题:
csvString
应为const char*
while
循环和逐个字符的手动副本。如您所见,该函数解析CSV行。
你需要:
csvToStrings
从该行获取每个值