C文件处理中的scanf/get问题
每当我运行这段代码时,获取“email”输入的最终scanf函数都不会执行,我会得到“updatesuccessfully!”直接留言!我尝试使用C文件处理中的scanf/get问题,c,file-handling,cfile,C,File Handling,Cfile,每当我运行这段代码时,获取“email”输入的最终scanf函数都不会执行,我会得到“updatesuccessfully!”直接留言!我尝试使用gets()而不是scanf,我也遇到了同样的问题。谁能给我解释一下这个问题吗 #包括 #包括 typedef结构目录 { 字符名称[20],电子邮件[20]; 长int电话; }目录; void add() { 目录d; 文件*文件; file=fopen(“phonebook.bin”、“ab”); 如果(!文件) printf(“打开文件失败!
gets()
而不是scanf,我也遇到了同样的问题。谁能给我解释一下这个问题吗
#包括
#包括
typedef结构目录
{
字符名称[20],电子邮件[20];
长int电话;
}目录;
void add()
{
目录d;
文件*文件;
file=fopen(“phonebook.bin”、“ab”);
如果(!文件)
printf(“打开文件失败!”);
其他的
{
printf(“输入名称:”);
scanf(“%[^\n]”,&d.name);
printf(“输入电话号码:”);
scanf(“%ld”和d.phone);
printf(“输入电子邮件ID:”);
scanf(“%[^\n]”,&d.email);
if(fwrite(&d,sizeof(目录),1,文件))
printf(“更新成功!”);
其他的
printf(“出现问题,请重试!”);
}
fclose(文件);
}
int main()
{
添加();
}
您的代码中存在多个问题
chara[10];//a在某种程度上等同于&a[0]。
在您的示例中,scanf()的第二个参数需要一个地址,而数组的名称已经是一个地址;数组第一个元素的地址void add()
{
Directory d;
FILE* file;
file = fopen("phonebook.bin", "ab");
if (!file)
printf("Failed to open file!");
else
{
printf("Enter the name: ");
scanf("%s", d.name); // ---> notice the %s format and the missing &
printf("Enter the Phone Number: ");
scanf("%ld", &d.phone);
printf("Enter the e-mail ID: ");
scanf("%s", d.email); // ---> same here
if (fwrite(&d, sizeof(Directory), 1, file))
printf("Updated successfully!");
else
printf("Something went wrong, Please try again!");
}
fclose(file);
}
在scanf中执行&d.email
,您将崩溃或获得未定义的行为
请在发帖前进行一些研究。Jayanth,谁或什么文本建议使用
scanf(%[^\n]”,…
?恢复Monica,我在网上读到过,它有助于阅读一行字符串,包括whit spacesJayanth,节省时间。使用fgets()
将一行读成字符串。scanf(%[^\n]”…
是一种糟糕的读取行的方法,存在许多问题。&d.name
和d.name
作为scanf()
参数是相同的地址,但类型不同-从技术上讲这是UB。OP的问题是1)不检查scanf()
的返回值,将其视为0作为scanf(%[^\n],&d.email);
不扫描上一行的'\n'
剩余内容。然后code使用统一的d.email
导致问题。请不要发布文本图片,将文本作为文本发布。scanf(“%s”,d.name);
与get(d.name)一样糟糕;
。两者都不应使用。没有宽度限制,也不检查scanf()
结果。稍微研究一下就会得出结论。%s“
将无法正确读取带有空格的名称,如“Alexandru Smeu”.正确。我回答了一个简短的问题。更深入地说,我100%同意你的观点。老实说,我不认为高中毕业后我曾使用过scanf(),但有一点是需要使用它的,这里似乎就是这样(大学作业初学者)。
void add()
{
Directory d;
FILE* file;
file = fopen("phonebook.bin", "ab");
if (!file)
printf("Failed to open file!");
else
{
printf("Enter the name: ");
scanf("%s", d.name); // ---> notice the %s format and the missing &
printf("Enter the Phone Number: ");
scanf("%ld", &d.phone);
printf("Enter the e-mail ID: ");
scanf("%s", d.email); // ---> same here
if (fwrite(&d, sizeof(Directory), 1, file))
printf("Updated successfully!");
else
printf("Something went wrong, Please try again!");
}
fclose(file);
}