[英]Reading a csv file into a struct in C using scanf
我在從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
,,,,,,,,,,.,(@,,▒
我還要面對的另一個問題是,文件中的某些數據在條目中將包含逗號,我將如何“忽略”這些逗號,使它們作為數據而不是文件中的分隔符出現?
再次,任何幫助將不勝感激。
編輯:這就是我所謂的功能:(即主要)
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)
}
讀取函數僅更新它通過值作為參數接收的局部變量node
。 您必須將指針傳遞給新分配的結構:
void readdata(bst_t *node) {
while (scanf(" %[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],[^,],%[^,],%[^,]",
node->data.ID, node->data.name, node->data.sex,
node->data.height, node->data.weight, node->data.team,
node->data.NOC, node->data.games, node->data.year,
node->data.season, node->data.city, node->data.sport,
node->data.event, node->data.medal) == 14) {
continue;
}
}
您可以通過以下方式從main
調用此函數:
int main(int argc, char *argv[]) {
bst_t node;
readdata(&node);
printdata(node);
return 0;
}
但是請注意,此功能不安全:它無法防止緩沖區溢出。
還要注意,它不能處理空字段,也不能處理帶有嵌入式逗號的字段。
為了正確地解析輸入,您需要一個處理特殊情況並提供精確錯誤報告的手動編碼解析器。
編輯:您發布的源代碼有語法錯誤:
node->data.event->node.data.medal) == 14)
它應顯示為:
node->data.event, node->data.medal) == 14)
continue;
你應該更可讀取格式化你的代碼,由4個空格縮進語句和周圍插入二元運算符和后位,
。
嘗試使用此版本的readdata
:(從網頁復制並粘貼)
void readdata(bst_t *node) {
while (scanf(" %[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],[^,],%[^,],%[^,]",
node->data.ID, node->data.name, node->data.sex,
node->data.height, node->data.weight, node->data.team,
node->data.NOC, node->data.games, node->data.year,
node->data.season, node->data.city, node->data.sport,
node->data.event, node->data.medal) == 14) {
continue;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.