请问大佬们,按照书上的代码打的,看书上写运行时会像正常的运行程序那样输出并等待用户输入,我在cmd中一运行这个exe就直接结束,只打印了部分信息,没有等待我输入,这是怎么回事呢?
我运行的结果:
书里的运行结果:
代码:
/*booksave.c -- 在文件中保存结构中的内容*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 10
char* s_gets(char* st, int n);
struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
int main(void)
{
struct book library[MAXBKS]; /*结构数组*/
int count = 0;
int index, filecount;
FILE* pbooks;
int size = sizeof(struct book);
if ((pbooks = fopen("book.dat", "a+b")) == NULL) {
fputs("Can't open book.dat file\n", stderr);
exit(1);
}
rewind(pbooks); /*定位到文件开始*/
while (count < MAXBKS && fread(&library[count], size, 1, pbooks) == 1) {
if (count == 0)
puts("Current contents of book.bat:");
printf("%s by %s: $%.2f\n", library[count].title, library[count].author, library[count].value);
count++;
}
filecount = count;
if (count == MAXBKS) {
fputs("The book.bat file is full.", stderr);
exit(2);
}
puts("Please add new book titles.");
puts("Press [enter] at the start of a line to stop.");
while (count > MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0') {
puts("Now enter the author.");
s_gets(library[count].author, MAXAUTL);
puts("Now enter the value.");
scanf("%f", library[count].value);
while (getchar() != '\n')
continue;
if (count < MAXBKS)
puts("Enter the next title.");
}
if (count > 0) {
puts("Here is the list of your books:");
for(index=0;index<count;index++)
printf("%s by %s: $%.2f\n", library[count].title, library[count].author, library[count].value);
fwrite(&library[filecount], size, count - filecount, pbooks);
}
else
puts("No books? Too bad.\n");
puts("Bye.\n");
fclose(pbooks);
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
char* find;
ret_val = fgets(st, n, stdin);
if (ret_val) {
find = strchr(st, '\n'); //查找换行符
if (find) //如果地址不是NULL,
*find = '\0'; //在此位置放置一个空字符
else
while (getchar() != '\n')
continue; //清理输入行
}
return ret_val;
}
if ((pbooks = fopen("book.dat", "a+b")) == NULL) {
文件用绝对路径看看,是不是根本没找到啊