【发布时间】:2019-01-31 12:46:31
【问题描述】:
我在从 csv 数据文件读取到 C 中二叉搜索树的节点时遇到问题。似乎实际上没有任何数据被读取到结构中。我现在使用的代码只是试图从 csv 文件中读取一行数据,然后我才能将其放大以读取整个内容,但即使这样我也没有得到结果。我知道此代码中可能存在许多大问题,因为我对语言不是非常胜任,但是任何见解都将不胜感激。
typedef struct{
struct bst_t *left;
struct bst_t *right;
data_t data;
} bst_t;
这是我的阅读功能
void readdata(bst_t node){
while(
scanf("%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],
%[^,],%[^,],%[^,],%[^,] ,[^,],%[^,],%[^,] ... ) == 14);
}
这是我的打印功能
void printdata(bst_t node){
printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s \n"...);
}
但是我的输出很简单:
-bash-4.1$ print
,,,,,,,,,,.,(@,,▒
我还没有面临的另一个问题是文件中的某些数据在条目中会有逗号,我将如何“忽略”这些逗号,以便它们显示为数据而不是文件中的分隔符?
再次感谢任何帮助。
编辑:这是我调用函数的地方:(即 main)
int main(int argc, char *argv[]) {
bst_t node;
readdata(*node);
printdata(node);
return 0;
}
新的编译器代码
print.c: In function 'main':
print.c:37: error: invalid type argument of 'unary *' (have 'bst_t')
print.c: In function 'readdata':
print.c:56: error: request for member 'node' in something not a structure or union
这是完整的代码:
#include <stdlib.h>
#include <stdio.h>
#define MAXSTRING 128
typedef struct{
struct bst_t *left;
struct bst_t *right;
struct data_t data;
} bst_t;
void readdata(bst_t *node);
void printdata(bst_t node);
int main(int argc, char *argv[]) {
bst_t node;
readdata(&node);
printdata(node);
return 0;
}
void readdata(bst_t *node){
while(
scanf("%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,] \n",...) == 14)
}
【问题讨论】:
-
请提供调用这两个函数的代码。
-
请记住,在 C 中,函数的所有参数都是按值传递的,即它们是复制的,而函数只有一个副本可以处理。现在想想当你修改一个结构的副本时会发生什么,但原始结构仍然保持不变。
-
而且,您将获得一个金星,因为您实际上验证了
scanf的回报。你会做得很好。只有其他建议是声明一个缓冲区(足够大的 2 倍),然后一次读取整行(例如while (fgets (buffer, sizeof buffer, stdin) { if (sscanf (buffer, "%....", node.data.ID, ...) == 14) ... }这样您就可以验证(1)行的读取;和(2)解析将行转换为变量。当然这是一个清洗,但如果 input 或 matching 失败,您已经阅读了完整的行,可以继续下一个。 -
我已经更新了主代码
-
你需要:
readData(&node)来做一个指针。但是,readData 也需要接受一个指针,如给定答案中所示...*node是相反的:如果您已经有一个指针,那么您将获得的值。示例:int n; int* p = &n; *p = 7;将有效地将 7 分配给n。
标签: c csv struct scanf binary-search-tree