我想從結構體中的文件中存儲信息。我的文件由行組成(每行必須是不同的結構)和列,每列都是不同的數據。文件看起來是這樣的:將空格分隔的文件轉換爲結構數組C
1 AB
2 CD
3 CD
4 AB
我的結構是這樣的(其中節點數量是第一個整數,節點類型是兩個字母):
struct nodes{
int nodeNumber;
char nodeType[2];
};
到目前爲止我的代碼是這樣的:
lines = lineCount(nodes); //calculates how many lines file has
struct nodes node[lines]; //creates structure array
no = fopen(nodes, mode);
if(no == NULL){
printf("Can't find the files.");
exit(1);
}else{
for(i = 0; i < lines; i++){
fscanf(no, "%d %2c \n", &id, current);
node[i].nodeNumber = id;
strcpy(node[i].nodeType, current);
}
}
當我調試當前值是:當前= \「AB \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \「而不只是AB
有什麼想法嗎?
「current」聲明如何?你看到的只是字符緩衝區中有nul個字節。因爲在C中沒有什麼可擔心的,nul字節表示字符串的結尾。還要注意,'strcpy'會嘗試在你的'nodeType'的末尾放置一個空字節,這會使緩衝區溢出。 –
我解決了我的問題,即使在我收錄的代碼中也是如此。感謝您的幫助! – Shepard