gpt4 book ai didi

c - 使用 sscanf 解析字符串

转载 作者:行者123 更新时间:2023-11-30 20:58:26 24 4
gpt4 key购买 nike

我的访问日志如下:

[Thu Oct  4 00:20:05.140 2018] 0.017 sec 0.017 sec [ext2/0/rel 53798 (0,10)] [question_description] @products_description"find ea"/1

我需要读取日期时间 [Thu Oct 4 00:20:05.140 2018] 和“find ea”之间的字符串。

我的代码:

int main(void) {
char buffer[10000];
int count = 0;
char datetime[35];
FILE* fptr;
fptr = fopen("query.log", "r");
while (count < 10) {
if (!fgets(buffer, sizeof buffer, fptr)) break;

sscanf(buffer,"%[^\n]", datetime);
printf("date : %s", datetime);

count++;
printf("\n");
}
return 0;
}

我需要更新 sscanf 的表达式,以便可以获得日期时间和字符串“xxxx”

最佳答案

你可以使用strtok来获取所需的字符串,这是我的解决方案:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char * tok;
char buffer[10000];
int count = 0;
char datetime[35];
char qdescription[35];
char pdescription[35];
FILE* fptr;

if(!(fptr = fopen("query.log", "r")))
{
perror("No file\n");
fclose(fptr);
return -1;
}

while(fgets(buffer, sizeof(buffer), fptr))
{
for(tok = strtok(buffer, "[]"); tok != NULL; tok = strtok(NULL, "[]"), count++)
{
switch(count)
{
case 0: strcpy(datetime, tok);

case 4: strcpy(qdescription, tok);

case 5: strcpy(pdescription, tok);
}
}
}

printf("%s\n%s\n%s\n", datetime, qdescription, pdescription);

return 0;
}

使用此代码,您可以检索日期和 question_description,我无法隔离最后一个 product_description,看看您是否可以找到解决此问题的方法。

关于c - 使用 sscanf 解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52655391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com