簡體   English   中英

C-從文件讀取字符串。 獲取隨機字符

[英]C - Reading string from a file. Getting random characters

該程序旨在讀取文件並在屏幕上打印讀取的內容(然后它接受另一個單詞,不知道這是否相關)。

FILE *dataMarking;
int x=0, y=0, letters, score;
char scanWord[10][20], currentWord[10][20], scanDescription1[10][40], scanDescription2[10][40], scanDescription3[10][40];

dataMarking = fopen("marking.dat", "r");

if (dataMarking == NULL){page=99;}

else{

x=0;
while (fscanf(dataMarking, "%s:%s:%s:%s\n", scanWord[x], scanDescription1[x], scanDescription2[x], scanDescription3[x]) == 2){x++;};

fclose(dataMarking);

x=0;
while(x<10){
    printf("%s\n",scanDescription1[x]);
    printf("%s\n",scanDescription2[x]);
    printf("%s\n",scanDescription3[x]);
    scanf("%s",currentWord[x]);
    x++;}

一旦打印到屏幕上,我會得到一系列隨機字符,而不是預期的文字。 上面是使用的代碼; 以下是文件中的信息。

one:The number 1:skip:skip
two:The number 2:skip:skip
three:The number 3:skip:skip
four:The number 4:skip:skip
five:The number 5:skip:skip
six:The number 6:skip:skip
seven:The number 7:skip:skip
eight:The number 8:skip:skip
nine:The number 9:skip:skip

提前致謝。

fscanf返回成功解析的參數數量。 fscanf有四個參數,而不是兩個。 您的循環將在第一次迭代時失敗,因為fscanf不會返回2。

while (fscanf(dataMarking, "%s:%s:%s:%s\n", scanWord[x], scanDescription1[x], scanDescription2[x], scanDescription3[x]) == 4

大概是這樣

x=0;
while (fscanf(dataMarking, "%[^:]:%[^:]:%[^:]:%[^\n]%*c", scanWord[x], scanDescription1[x], scanDescription2[x], scanDescription3[x]) == 4){x++;}

fclose(dataMarking);

for(y=0;y<x;++y){
    printf("%s\n",scanDescription1[y]);
    printf("%s\n",scanDescription2[y]);
    printf("%s\n",scanDescription3[y]);
    printf("%s\n",scanWord[y]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM