gpt4 book ai didi

c - 如何在 C 中读取具有不同格式的多行 TXT 文件?

转载 作者:太空宇宙 更新时间:2023-11-04 02:23:13 24 4
gpt4 key购买 nike

我有一个看起来像这样的输入文本文件:

1(1.230000e+00)
2(1.230000e+00)
(1.230000e+00 1.230000e+00)
3(1.230000e+00)
(1.230000e+00 1.230000e+00)
.
.
.

我希望能够分别阅读每一行并区分它们。例如,对于第一行,我想将 100 作为 int 存储在一个变量中,并且我想将 1.230000e+00 存储在另一个变量作为 double。这是我尝试过的:

fscanf(fp, "%d(%le)\n", &varInt, &varDouble);

这适用于第一行。但是我怎样才能遍历并对所有行执行此操作并使用以下方法读取第 3 行:

fscanf(fp, "(%le %le)\n", &varDouble1, &varDouble2);

为了提供一些上下文,在阅读每一行之后,我将进行一些处理,然后再阅读下一行。根据行的格式,我会做不同类型的处理。

感谢任何帮助!谢谢!

最佳答案

fscanf(3) 除非严格控制输入,否则几乎无法使用。很难区分 I/O 错误和解析错误。这就是为什么更常见的是使用 fgets(3) 读取每一行,然后使用 sscanf(3) 扫描它。

因为 sscanf 返回已解析的元素数,您可以使用它来确定扫描是否按预期进行。无需查看输入:如果你得到了预期的结果,你就完成了,否则请尝试以其他方式扫描。这是一个工作示例:

#include <assert.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>

int
main( int argc, char *argv[] ) {
if( argc < 2 ) {
errx(EXIT_FAILURE, "syntax: %s filename", argv[0]);
}

FILE *input = fopen(argv[1], "r");
if( !input ) {
err(EXIT_FAILURE, "could not open '%s'", argv[0]);
}

static char line[128];
int n;

while( fgets(line, sizeof(line), input) != NULL ) {
double d1, d2;
int quantum;

if( 2 == sscanf(line, "%d(%lf)", &quantum, &d1) ) {
printf( "ok: %d\t%7.2f\n", 100 * quantum, d1 );
} else if( 2 == sscanf(line, "(%lf %lf)", &d1, &d2) ) {
printf( "ok: %7.2f\t%7.2f\n", d1, d2 );
} else {
printf( ">>> %s\n", line );
}

}

if( !feof(input) ) {
err(EXIT_FAILURE, "error reading %s", argv[1]);
}

return EXIT_SUCCESS;
}

如果您发现其他模式,添加它们很容易。请注意,当 fgets 失败时,程序仅在我们到达文件末尾时才返回成功。

关于c - 如何在 C 中读取具有不同格式的多行 TXT 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54858673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com