【发布时间】:2015-07-27 12:49:05
【问题描述】:
我有一个 csv 文件,其中有 2 列命名;时间戳,SNR(整数值)。我必须编写一个首先询问用户输入的函数;用户想要什么价值? 示例文件:
timestamp ; SNR
16:15:12:468 ; 15
16:15:12:968 ; 20
例如:如果我输入 SNR,函数应该给我列号。信噪比; (即此处的第 2 列)以及 SNR 的值。
Output : Col. no. is 2
15 /* time difference of ((16:15:12:968)-(16:15:12:458) = 500ms between these two output values*/
20
但是这些值应该在某个时间间隔内作为输出给出。这意味着必须首先读取时间戳列,并且应该计算两个时间戳(当前和下一个)值之间的差异。现在应该在这两个时间戳值之间的差异间隔上给出 SNR 作为输出。我不想使用数组或结构,因为我不想存储值;我只是要求这些值在特定的时间间隔内传递给其他应用程序。
我写了以下代码。我可以获得用户输入并输出列号。文件,但我无法获取这些列的内容。我在我的程序中使用了 switch case,但我不明白为什么这个 switch case 不起作用。我还编写了一个函数来获取这两个时间戳之间的时间差,但我不知道如何在这个函数中组合它。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <time.h>
#define BUFFER_SIZE 1024
#define num_rows 100
const char* gettime(char* line, int num )
{
const char* tok;
for (tok = strtok(line, ";");tok && *tok;tok = strtok(NULL, ";\n"))
{
if (!num--)
//Sleep(500);
return tok;
}
return NULL;
}
const char* getSNR(char* line, int num )
{
const char* tok;
for (tok = strtok(line, ";");tok && *tok;tok = strtok(NULL, ";\n"))
{
if (!num--)
//Sleep(500);
return atoi(tok);
}
return NULL;
}
struct tm mytime;
int main ()
{
int hh, mm;
float ss, ms;
mytime.tm_year = 2015 - 1900; /* To initialize the struct tm*/
mytime.tm_mon = 6;
mytime.tm_mday = 15;
int count;
int value;
char text[25];
char *buffer;
FILE *fp;
char *token;
char *tok;
char line [100];
char time_buffer[100];
char **timestamp; /*Dynamic allocated array*/
unsigned long ul_second_prev ;
unsigned long ul_second_current;
int i=0, j=0, k=1;
int ui_time_diff, ui_SNR;
time_t time_prev, time_current; /*Dynamic allocated array*/
int timediff ;
timestamp = malloc(num_rows*sizeof(char*));
if ((timestamp)== NULL)
{
printf("Error: out of memory");
}
if ((fp=fopen("testfile.csv", "r"))==NULL)
{
printf ("file cannot be opened");
return 1;
}
buffer = malloc (BUFFER_SIZE); /*Allocate memory in buffer to read the file*/
if (buffer == NULL)
{
printf("Error: Out of Memory");
return 1;
}
fgets(line, BUFFER_SIZE, fp);
printf ("%s", line);
printf ("enter your input\n");
scanf("%s" , &text);
for (tok = strtok(line, ";");tok && *tok;tok = strtok(NULL, ";\n"))
{
value = strcmp (tok, text);
if(value ==0)
printf("col. no. is %d", k);
else k++ ;
}
while (fgets(line, BUFFER_SIZE, fp))
{
char* tmp = strdup(line);
switch (k)
{
case 1:
gettime(tmp, 1);
printf ( "%s",tok );
break;
case 2:
getSNR(tmp, 2);
printf ( "%s",tok );
break;
}
free(tmp);
}
【问题讨论】:
-
SNR 应该是多少??
-
SNR 只是 int 值,例如 15、20、25 等。
-
然后只写“值”而不是“信噪比”。当你问一个问题时,要笼统,不要使用只有你理解的术语。您还应该给出一些输入以及期望和实际输出的示例。
-
请缩进代码以使其可读......
volatile应该在这里做什么?我没有看到任何信号或硬件寄存器访问......哦,您输入格式中的分号在哪里?有点混乱…… -
@AntoineL 逗号就是逗号。是的,通常的做法是调用任何 csv,只要它具有使用 some 分隔符的值的行,但这并不能使它正确....在真正的 csv 中,一个包含逗号的值必须用双引号括起来...