在C中读取文件时,输入正确,但输出不正确



我有一个结构,它应该包含一个单词、它对应的数字和它的线索。

struct Word{
char word[30];
int level;
char clue[500];
};
typedef struct Word Word;

我通过以下函数操作它。

void createWord(){ //creates a word
FILE *fp;
fp = fopen("words.bin", "a+"); 
if(!fp){
printf("File could not be opened.n");
}else{
Word w;
w.level = getLevel(); //gets level number in the list
getchar();
printf("Enter word: ");
scanf("%[^n]s", w.word); //asks for the word
getchar();
printf("Enter clue: ");
scanf("%[^n]s", w.clue); //asks for the clue
getchar();

//i used this to trace the values
printf("n%d", w.level);
printf("n%s", w.word);
printf("n%s", w.clue);

//goes through the file and writes the content in it
fseek(fp, sizeof(Word)*(w.level - 1), SEEK_SET);
fwrite(&w, sizeof(Word),1, fp);
fclose(fp);
}
}
int getLevel(){
FILE *fp;
fp = fopen("words.bin", "r");
fseek(fp,0,SEEK_END);
int n = ftell(fp)/sizeof(Word); //tells me the number of 'Words' that are already in the file
fclose(fp);
return n++;
}
void displayContent(){ //displays all the content inside the file
FILE *fp;
fp = fopen("words.bin", "rb");
if(!fp){
printf("File could not be opened.n");
}else{
Word w;
while(fread(&w, sizeof(Word), 1, fp) && !feof(fp)){
printf("n");
printWord(&w);
}
fclose(fp);
}
}
void printWord(struct Word *w){
printf("Level: %dn", w->level+1);
printf("Word: %sn", w->word);
printf("Clue: %sn", w->clue);
}

这里有一个最小的可复制示例:

int main(){
int choice;
Word w;
do{
printf("nn1. Create Wordn");
printf("2. Diplay all wordsn");
printf("3. Exitn");
printf("n? ");
scanf("%d", &choice);
switch(choice){
case 1:
createWord();
break;
case 2:
displayContent();
break;
default:
break;
}
}while(choice != 3);
return 0;
}

我的主要问题是我输入了正确的值。每当我在执行函数之前检查它时,它的读数都是正确的。但是,当我尝试显示文件中的所有内容时,输出完全不稳定。下面是一个例子。

Level: 1 //this one is correct
Word: Uno
Clue: The grade our teacher will give us by the end of the semester.

Level: 257 //this one is not, this is supposed to be 2
Word: vBo Burnham // this is supposed to be Bo Burnham only
Clue: //and this is supposed to print a sentence like 'Go listen to his new album'

我认为这与getchar()有关,但我也不太确定。任何形式的帮助都将不胜感激!

void createWord(){
FILE *fp;
fp = fopen("words.bin", "a+");
if(!fp){
printf("File could not be opened.n");
}else{
Word w;
char tempWord[30];
char tempClue[100];
int tempNum;
tempNum = getLevel();
fgetc(stdin);
printf("Enter word: ");
fgets(tempWord, 30, stdin);
tempWord[strlen(tempWord)-1] = 0;
printf("Enter clue: ");
fgets(tempClue, 100, stdin);
tempClue[strlen(tempClue) - 1] = 0;
w.level = tempNum;
strcpy(w.word, tempWord);
strcpy(w.clue, tempClue);
printf("n%d", w.level);
printf("n%s", w.word);
printf("n%s", w.clue);
fwrite(&w, sizeof(Word), 1, fp);
fclose(fp);
}
}

n让它变得不稳定。现在仍然是这样,但它有效。

最新更新