这是我的这一段代码,当scanf时
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef struct {
char name[20];
int wuwen;
int shuxue;
int yingyu;
int number;
}student;
typedef struct listnode {
student data;
struct listnode* next;
}listnode, * linklist;
linklist l = NULL;
FILE* fp;
char filename[100];
void createlist() {
l = (listnode*)malloc(sizeof(listnode));
l->next = NULL;}
void openfile() {
createlist();
listnode* p, * q;
q = l;
while (true) {
printf("\n\n\t\t\t请输入文件名:");
scanf("%s", &filename);
if ((fp = fopen(filename, "r")) == NULL) {
printf("\t\t\t没有该文件,需要创建s\n");
char ch; scanf("%c",&ch);
if (ch == 's') {
if ((fp = fopen(filename, "a+")) == NULL) {
printf("\t\t\t创建文件失败\n");
}
else break;
}
else continue;
}
else break;
}
while (true) {
p = (listnode*)malloc(sizeof(listnode));
if (fscanf(fp, "%d\t%s\t%d\t%d\t%d", &p->data.number, &p->data.name, &p->data.wuwen, &p->data.shuxue, &p->data.yingyu) == EOF) {
free(p);
printf("\t\t\t读入成功\n");
system("pause");
break;
}
p->next = NULL;
q->next = p;
q = q->next;
}
fclose(fp);
}
int main() {
openfile();
}
当为cin时,就可以解决这个问题
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef struct {
char name[20];
int wuwen;
int shuxue;
int yingyu;
int number;
}student;
typedef struct listnode {
student data;
struct listnode* next;
}listnode, * linklist;
linklist l = NULL;
FILE* fp;
char filename[100];
void createlist() {
l = (listnode*)malloc(sizeof(listnode));
l->next = NULL;}
void openfile() {
createlist();
listnode* p, * q;
q = l;
while (true) {
printf("\n\n\t\t\t请输入文件名:");
scanf("%s", &filename);
if ((fp = fopen(filename, "r")) == NULL) {
printf("\t\t\t没有该文件,需要创建s\n");
char ch; cin >> ch;
if (ch == 's') {
if ((fp = fopen(filename, "a+")) == NULL) {
printf("\t\t\t创建文件失败\n");
}
else break;
}
else continue;
}
else break;
}
while (true) {
p = (listnode*)malloc(sizeof(listnode));
if (fscanf(fp, "%d\t%s\t%d\t%d\t%d", &p->data.number, &p->data.name, &p->data.wuwen, &p->data.shuxue, &p->data.yingyu) == EOF) {
free(p);
printf("\t\t\t读入成功\n");
system("pause");
break;
}
p->next = NULL;
q->next = p;
q = q->next;
}
fclose(fp);
}
int main() {
openfile();
}
所以,我就是想知道,为什么scanf会引起这样的错误