C - 从文件中读取字符串。获取随机字符

时间:2014-02-04 22:24:18

标签: c string file printing

此程序旨在从文件中读取并打印读取到屏幕的内容(然后它接受另一个单词,不知道这是否相关)。

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

提前致谢。

2 个答案:

答案 0 :(得分:0)

fscanf返回成功解析的参数数量。 fscanf有四个参数而不是两个。您的循环将在第一次迭代时失败,因为fscanf不会返回2.

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

答案 1 :(得分:0)

可能是这样的,

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]);
}