c/c++语言开发共享如何在文件*流中的特定点停止并扫描某些值?

我有一个名为test.txt的文件,该文件包含:

  10.213123 41.21231 23.15323   

当我看到我希望扫描后的3个数字,如下所示:

 x = 10.213123 y = 41.21231 z = 23.15323 

我有点困惑,因为在这里,fgets扫描整条线,我怎样才能将3个数字扫描成双线? 因为数字可以是各种长度? 我这样做是为了打印出它从文件中读取的内容,但我无法绕过它。

 void print_lines(FILE *stream) { char line[MAX_LINE_LENGTH]; while (fgets(line, MAX_LINE_LENGTH, stream) != NULL) { fputs(line, stdout); } } 

    就在你看到然后将3个数字扫描成双倍。 你有line变量的行内容,你可以使用strtod将字符串扫描成double。 你甚至可以使用sscanf(line, "%lf %lf %lf", &x, &y, &z); ,但使用strtod更适合error handling。

     #define _GNU_SOURCE #include  #include  #include  #include  #include  #define MAX_LINE_LENGTH 1024 void print_lines(FILE *stream) { double a, b, c; char line[MAX_LINE_LENGTH]; while (fgets(line, MAX_LINE_LENGTH, stream) != NULL) { char *pnt; // locate substring `` in the line if ((pnt = strstr(line, "") != NULL)) { // advance pnt to point to the characters after the `` pnt = &pnt[sizeof("") - 1]; char *pntend; // scan first number a = strtod(pnt, &pntend); if (pnt == pntend) { fprintf(stderr, "Error converting a value.n"); // well, handle error some better way than ignoring. } pnt = pntend; // scan second number b = strtod(pnt, &pntend); if (pnt == pntend) { fprintf(stderr, "Error converting a value.n"); // well, handle error some better way than ignoring. } pnt = pntend; // scan third number c = strtod(pnt, &pntend); if (pnt == pntend) { fprintf(stderr, "Error converting a value.n"); // well, handle error some better way than ignoring. } printf("Read values are %lf %lf %lfn", a, b, c); } else { // normal line //fputs(line, stdout); } } } int main() { print_lines(stdin); return 0; } 

      以上就是c/c++开发分享如何在文件*流中的特定点停止并扫描某些值?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522017.html

      (0)
      上一篇 2020年12月9日
      下一篇 2020年12月9日

      精彩推荐