如何停止在文件流中的特定点并扫描某些值? [英] How do I stop at a particular point in a file *stream and scan in some values?
问题描述
我有一个名为test.txt的文件,该文件包含:
I have a file called test.txt the file contains:
<this is a test = 1>
<more tests = 42 and more "34">
<start>10.213123 41.21231 23.15323</start>
<random stuff = "4">
<blah 234>
当我看到< start>
想要在3个数字之后扫描成这样的两倍:
When I see <start>
I want to scan in the 3 numbers after into a double like this:
x = 10.213123
y = 41.21231
z = 23.15323
我有点困惑,因为在这里,fgets会扫描整行,我该如何将3个数字扫描成双倍?因为数字可以有不同的长度?我这样做是为了打印出它从文件中读取的内容,但是我无法将其包裹住。
I'm sort of confused because here, fgets scans the entire line, how can I scan in the 3 numbers into a double? Because the numbers can be of various lengths? I made this to print out what it reads from a file but I can't wrap my head around it.
void print_lines(FILE *stream) {
char line[MAX_LINE_LENGTH];
while (fgets(line, MAX_LINE_LENGTH, stream) != NULL) {
fputs(line, stdout);
}
}
推荐答案
当您看到< start>
时,将3个数字扫描成两倍。您在 line
变量中具有行内容,可以使用 strtod 将字符串扫描成两倍。您甚至可以使用 sscanf(line,< start>%lf%lf%lf< / start>,& x,& y,& z);
,但是使用strtod更好地处理错误。
Just when you see <start>
then scan 3 numbers into double. You have the line content in line
variable, you can use strtod to scan string into double. You can even use sscanf(line, "<start>%lf %lf %lf</start>", &x, &y, &z);
, but using strtod is better for error handling.
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stddef.h>
#include <stdlib.h>
#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 `<start>` in the line
if ((pnt = strstr(line, "<start>") != NULL)) {
// advance pnt to point to the characters after the `<start>`
pnt = &pnt[sizeof("<start>") - 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;
}
这篇关于如何停止在文件流中的特定点并扫描某些值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!