gpt4 book ai didi

c - 逐步执行可变长度的整数行

转载 作者:行者123 更新时间:2023-11-30 17:33:12 25 4
gpt4 key购买 nike

我正在尝试读取一个有点像这样的文件...

52 12 123 1
4 2 11
9 88 1 23 42

文件随着每一行的变化而继续我知道如何使用 fscanf 循环单独读取每个数字,但我想读取第一个数字作为树中的父级,而该行的其余部分作为其子级。所以这将构成 3 棵树,其中 52、4 和 9 是父树。我应该如何阅读该行的其余部分并将每个 int 添加到正确的树中?我正在用 c 编写这个代码。

最佳答案

按行读取然后将行输入解析为整数可能会提供更多的灵 active 。使用指针逐步遍历各行,直到找到空终止符为止,以适应每行不同数量的整数。以下是对解决方案的快速破解,该解决方案在提供的示例输入上表现良好。代码是:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main (int argc, char *argv[]) {

if (argc < 2 ) {
fprintf (stderr, "Error: insufficient input, usage: %s char *fname\n", argv[0]);
return 1;
}

FILE *file;
char *lineptr = NULL;
char *sptr = NULL, *eptr = NULL;
size_t n = 0;
ssize_t len = 0;
int cnt = 0;
int parent = 1;

if ((file = fopen (argv[1], "r")) == NULL) {
fprintf (stderr, "Error: file open failed for '%s'\n", argv[1]);
return 1;
}

while ((len = getline (&lineptr, &n, file)) != -1 ) {
/* strip newline */
if (*(lineptr+len-1) == '\n') {
*(lineptr+len-1) = '\0';
len -= 1;
}

/* test output of line to parse */
printf ("\nLine [%2d]: \"%s\"\n\n", cnt, lineptr);

/* parse line into integers */
parent = 1;
sptr = NULL;
eptr = lineptr;
while (*eptr != '\0') {
if (*eptr != ' ' && sptr == NULL) {
sptr = eptr;
eptr++;
}
while (*eptr != ' ' && *eptr != '\0') {
eptr++;
}

if (*eptr == '\0') {
printf (" add to tree: %d\n", atoi (sptr));
break;
}

if (*eptr == ' ' && sptr != NULL) {
*eptr = '\0';
if (parent) {
printf (" add to tree: %d (parent)\n", atoi (sptr));
parent = 0;
} else {
printf (" add to tree: %d\n", atoi (sptr));
}
*eptr = ' ';
sptr = NULL;
}

eptr++;
}
cnt++;
}

printf ("\nTotal lines parsed: %d\n\n", cnt);

return 0;
}

示例数据的输出为:

Line [ 0]: "   52 12 123 1"

add to tree: 52 (parent)
add to tree: 12
add to tree: 123
add to tree: 1

Line [ 1]: " 4 2 11"

add to tree: 4 (parent)
add to tree: 2
add to tree: 11

Line [ 2]: " 9 88 1 23 42"

add to tree: 9 (parent)
add to tree: 88
add to tree: 1
add to tree: 23
add to tree: 42

Total lines parsed: 3

我确信有一种更快的方法可以做到这一点,但简单地单步执行带有指针的行可以消除调用字符串函数所需的相当多的开销。我不知道您正在考虑什么类型的树,但此代码提供了一种简单的方法来在当前 printfs 所在的位置添加插入例程。

关于c - 逐步执行可变长度的整数行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23841423/

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