如何在c中浮点数后面紧跟字母'e'的floatf进行扫描? [英] How to scanf a float followed immediately by the letter 'e' in c?
问题描述
我正在尝试使用 fscanf
读取数据,部分输入是浮点数,后跟字母'e'
,例如 41.72过去
.在为 fscanf
编写strng时,我尝试使用%felapsed"
,但这是行不通的,因为%fe
是它自己的格式说明符.我将如何使用 fscanf
来阅读此内容?
I'm trying to use fscanf
to read in data, and part of the input is a float followed by the letter 'e'
, for example, 41.72elapsed
. When writing the strng for fscanf
, I attempted to use "%felapsed"
, but this doesn't work, as %fe
is its own format specifier. How would I read this in using fscanf
?
这是代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define CHAR_MAX 1024
int main(int argc, char **argv)
{
FILE *file_in = fopen(argv[1], "r+");
char out_name[CHAR_MAX];
strcpy(out_name, argv[1]);
strcat(out_name, ".csv");
FILE *csv_out = fopen(out_name, "w");
int minutes;
float seconds;
fprintf(csv_out, "Trial #, Execution Time\n");
for (int i = 0; fscanf(file_in, "%*fuser %*fsystem %d:%felapsed %*d%%CPU (%*davgtest+%*davgdata %*dmaxresident)k\n%*dinputs+%*doutputs (%*dmajor+%*dminor)pagefaults %*dswaps\n", &minutes, &seconds) == 2; i++) {
fprintf(csv_out, "%d, %d:%.2f\n", i, minutes, seconds);
};
return 0;
}
以下是一些示例输入:
283.97user 0.69system 1:13.77elapsed 385%CPU (0avgtext+0avgdata 107472maxresident)k
0inputs+4616outputs (0major+9550minor)pagefaults 0swaps
287.87user 0.35system 1:14.41elapsed 387%CPU (0avgtext+0avgdata 107328maxresident)k
0inputs+4616outputs (0major+9524minor)pagefaults 0swaps
推荐答案
这是 scanf()
FP格式将 e
引入了幂运算.由于 e
后没有数字,因此将停止扫描 float
.但是 scanf()
都已经准备好在 e
之后进行一次扫描,并且C不需要 scanf()
可以备份更多内容.1个字符.因此,使用简单的%f"
运气不好.
FP formats like "%f"
see the e
as introducing exponentiation. Since the e
is not followed by a number, scanning for the float
stops. But scanf()
has all ready scanned one past the e
and C does not require for scanf()
to be able to back up more than 1 character. So code is out-of-luck using a simple "%f"
.
某些系统将备份1个以上的字符,但是C不需要该功能.
Some systems will back up more than 1 character, but C does not require that capability.
代码需要一种新方法-以秒为单位扫描字符串
Code needs a new approach - scan in seconds as a string
char sec[20];
int cnt = fscanf(file_in, "%d:%19[0-9. ]elapsed", &minutes, sec);
if (cnt == 2) {
seconds = atof(sec);
...
}
这篇关于如何在c中浮点数后面紧跟字母'e'的floatf进行扫描?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!