问题
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>
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
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);
}
}
回答1:
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;
}
来源:https://stackoverflow.com/questions/50874230/how-do-i-stop-at-a-particular-point-in-a-file-stream-and-scan-in-some-values