如何在文件*流中的特定点停止并扫描某些值?

我有一个名为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 %lf\n", a, b, c); } else { // normal line //fputs(line, stdout); } } } int main() { print_lines(stdin); return 0; }