gpt4 book ai didi

c - 从多维数组中提取时序并写入c中的文件

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

我在从 .srt 中提取时间时遇到问题(字幕)文件并将其写入另一个名为 output.srt 的文件。当我运行以下命令时,我会在输出文件中写入一些有趣的内容。

//其中 hr=小时,mn=分钟,sc=秒,ms=毫秒

#include <stdio.h>
#define LINES 50
#define CHARAC 80
int main(void){
FILE *in;
FILE *out;
char text[LINES][CHARAC];
char timings[LINES][CHARAC];
int i=0,lines=0,items=0;
int hr=0,mn=0,sc=0,ms=0,hr2=0,mn2=0,sc2=0,ms2=0;

in=fopen("file2.srt","r");
out=fopen("output.srt","w");

while (!feof(in)){
fgets(text[i],80,in);
items=sscanf(text[i],"%d:%d:%d,%d --> %d:%d:%d,%d ",&hr,&mn,&sc,&ms,&hr2,&mn2,&sc2,&ms2);
//------------------------------------->edited<----------------------------------
switch (items)
{
case 1: break;
case 8:
sprintf(timings[i],"%d:%d:%d,%d --> %d:%d:%d,%d",hr,mn,sc,ms,hr2,mn2,sc2,ms2);
break;
case 0: break;

}
//------------------------------------->edited<----------------------------------
++i;
}
lines=i;

for (int i=0;i<lines;i++){
fprintf(out,"%s\n",timings[i]);
}

fclose(in);
fclose(out);

return 0;
}

如何提取前 10 个时间?

最佳答案

如果这是在 Windows(或 MSDOS)上,则打开模式需要是文本:

in =  fopen ("file2.srt", "rt");
out = fopen ("output.srt", "wt");

其次,代码没有对不同格式的行做出任何反应。前几行数据是:

1
00:00:30,909--> 00:00:32,775
Take a look at yourself.

2
00:00:34,066--> 00:00:37,681
Disconnect you from the seats,
lift yourself and take a look in the mirror.

因此,自然地,第一个 sscanf 不会填充大部分字段。这是我得到的输出(对于相应的行):

1:0:0,0 --> 0:0:0,0
0:0:30,909 --> 0:0:32,775
0:0:30,909 --> 0:0:32,775
0:0:30,909 --> 0:0:32,775
2:0:30,909 --> 0:0:32,775

要解决此问题,您必须添加需要正确数量的元素的逻辑,或者至少对它们使用react:

itms = sscanf(text[i],"%d:%d:%d,%d --> %d:%d:%d,%d ",&hr,&mn,&sc,&ms,&hr2,&mn2,&sc2,&ms2);
switch (itms)
{
case 1: // the first line
case 8: // the lines with the times
case 0: // the text lines
}

已编辑以添加上次编辑的固定版本:

#include <stdio.h>
#define LINES 50
#define CHARAC 80
int main(void){
FILE *in;
FILE *out;
char text[LINES][CHARAC];
char timings[LINES][CHARAC];
int i=0,lines=0,items=0;
int hr=0,mn=0,sc=0,ms=0,hr2=0,mn2=0,sc2=0,ms2=0;

in=fopen("file2.srt","rt");
out=fopen("output.srt","wt");

while (!feof(in))
{
if (!fgets(text[i],80,in))
break;
items = sscanf(text[i], "%d:%d:%d,%d --> %d:%d:%d,%d ", &hr,&mn,&sc,&ms,&hr2,&mn2,&sc2,&ms2);
switch (items)
{
case 1: break;
case 8:
sprintf(timings[i],"%d:%d:%d,%d --> %d:%d:%d,%d",hr,mn,sc,ms,hr2,mn2,sc2,ms2);
++i; // advance only when a valid line is seen
break;
case 0: break;
}
}
lines=i;

for (i=0; i<lines; i++){
fprintf(out,"%s\n",timings[i]);
}

fclose(in);
fclose(out);

return 0;
}

关于c - 从多维数组中提取时序并写入c中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1844754/

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