C 当存在';他们之间有一条线

C 当存在';他们之间有一条线,c,string,integer,file-handling,fseek,C,String,Integer,File Handling,Fseek,我试图使用循环从文件中读取多个整数。我面临的问题是在这些整数之间有一个字符串。我的目标是找到文件中的最后一个整数 示例:-123你好1253世界 在上面的例子中,最后一个整数是1253 int id; p=fopen("o.txt","r"); while(!feof(p)) { fscanf(p,"%d",&id); fseek(p,13,SEEK_CUR); } ``` I used `fseek

我试图使用循环从文件中读取多个整数。我面临的问题是在这些整数之间有一个字符串。我的目标是找到文件中的最后一个整数 示例:-
123你好1253世界
在上面的例子中,最后一个整数是1253

int id;
p=fopen("o.txt","r");
while(!feof(p))
{
    fscanf(p,"%d",&id);
    fseek(p,13,SEEK_CUR);
} ```

   

I used `fseek()` to jump over the string. There were 13 characters from the last digit to the beginning of the next digit.
This does not work and I ended up in an infinite loop.
Can anyone help?
Thank you
我的目标是找到文件ex:-123 hello 1253 world中的最后一个整数,所以在上面的例子中,最后一个整数是1253

int id;
p=fopen("o.txt","r");
while(!feof(p))
{
    fscanf(p,"%d",&id);
    fseek(p,13,SEEK_CUR);
} ```

   

I used `fseek()` to jump over the string. There were 13 characters from the last digit to the beginning of the next digit.
This does not work and I ended up in an infinite loop.
Can anyone help?
Thank you
while(!feof(p))
-->

缓慢的解决方案:读取整个文件。寻找整数。如果下一个输入不是整数,则将输入作为字符使用并丢弃它(测试EOF)


其他想法,到最后。重复向后搜索直到失败,或向前读取生成一个整数

未经检验的想法。它本身并没有那么有效,而是给OP一个想法

long offset = 0;
while (fseek(p,--offset,SEEK_END) == 0) {
  long long last;
  if (fscanf(p, "%lld", &last)==1) {
    while (fseek(p, --offset, SEEK_END) == 0) {
      long long i;
      if (fscanf(p, "%lld", &i)==1) {
         last = i;
      }
    }
    printf("Last: %lld\n", last);
    break;
  }
}
    

ftell(),fseek()
作为
fseek()
的文本文件使用到除开始位置以外的任何位置或相对于上一个
ftell()
结果是错误的。考虑使用<代码>“RB”< /代码>。

使用<代码> fgs<代码>读取一行。然后使用
strtok
将字符串解析为标记。或者使用多个
fscanf
格式说明符-每个令牌一个。仅供参考。您可以使用…
%c
。。。然后尝试在int上转换,如果convert返回true,则将该数字保存到int变量中,否则,丢弃该字符并读取下一个字符,对于从字符到int的转换,我建议使用
strtol