您好,我正在嘗試從 CSV 檔案中讀取資料,通過“,”對其進行決議,并嘗試將用戶和密碼存盤到兩個不同的陣列中。但是,我無法將令牌資料存盤到字串陣列中。我不確定如何修復它:(。
這是我的代碼,
#include<stdio.h>
int main(){
FILE *fptr;
char row[100];
char usr[100][100];
char pwd[100][100];
fptr = fopen("users.csv", "r");
int i = 0;
int j = 0;
while( fgets(row, 100, fptr) ){
char *token;
token = strtok(row, ",");
strcpy(usr[i], token);
while(token != NULL){
printf("%s", token);
strcpy(pwd[i], token);
printf("\n");
}
i ;
printf("\n");
}
for(int k = 0; i < 100; i ){
if(usr[k] == NULL || pwd[k] == NULL)
break;
printf("%s", usr[k]);
printf("%s", pwd[k]);
}
}
我得到以下輸出:

uj5u.com熱心網友回復:
您的問題是第一個回圈中的第二個 while 回圈。那沒有終止條件,因為它一直進入無限回圈。
就像評論中提到的Craig Estey一樣,您可以保留 while 回圈并添加另一個 strtok(NULL, row) 以確保您讀取整行而不是只讀取第一個標記(在這種情況下,第一個之前的字串逗號一行)。或者,如果您確定一行中只會有 2 列,那么您可以呼叫 strtok 兩次來讀取這兩個標記并將它們分配給您的陣列。
此外,您的最終列印回圈是錯誤的。默認情況下,C 中的字符陣列未使用 NULL 進行初始化,因此檢查 NULL 將不起作用,除非您首先回圈并在開始檔案處理之前將所有內容設定為 NULL。相反,跟蹤您從檔案中讀取的行數,然后將其用作回圈計數器來列印您的變數。
本質上,這樣的事情會起作用:
FILE *fptr;
char row[100];
char usr[100][100];
char pwd[100][100];
fptr = fopen("users.csv", "r");
int lineCounter = 0;
while( fgets(row, 100, fptr) ) {
char *token;
token = strtok(row, ",");
strcpy(usr[lineCounter], token);
token = strtok(NULL, ",");
while(token != NULL) { // What this does is if your line is malformed like "ABC,123,12334,12233,Abc" then usr[i] would be ABC and pwd[i] would be Abc. It will only consider the first and last tokens.
strcpy(pwd[lineCounter], token);
token = strtok(NULL, ",");
}
lineCounter ;
}
for(int k=0; k < lineCounter; k ) {
printf("User: %s -- Password: %s\n", usr[i], pwd[i]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533907.html
標籤:C细绳文件
上一篇:將表示<img>標簽的字串的一部分收集到Java8中的串列中
下一篇:保留串列的唯一元素
