c - 为什么我的代码即使正确也不起作用?
问题描述
这是我的代码的一部分。它有 0 个错误和 0 个警告,但它不起作用。这是完全正确的。但它不起作用。
#include<stdio.h>
struct details{
char empName;
int age;
float salary;
}det1;
void main(){
printf("Please enter a name : ");
scanf("%s",&det1.empName);
printf("Please enter the age : ");
scanf("%d",&det1.age);
printf("Please enter the salary : ");
scanf("%f",&det1.salary);
FILE *p;
p = fopen("employee.txt","w");
fprintf(p,"%s %d %0.2f",det1.empName,det1.age,det1.salary);
fclose(p);
}
解决方案
关于 OPs 发布的代码:
通过启用了最有用警告的编译器运行它会导致:
gcc -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled2.c"
untitled2.c:9:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
void main(){
^~~~
untitled2.c: In function ‘main’:
untitled2.c:20:17: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
fprintf(p,"%s %d %0.2f",det1.empName,det1.age,det1.salary);
~^ ~~~~~~~~~~~~
%d
所以它不能干净地编译。
然后这个声明:
scanf("%s",&det1.empName);
正在尝试将无限长度的字符插入单个字符。
建议修改:
struct details{
char empName;
int age;
float salary;
}det1;
进入:
struct details <-- struct definition
{
char empName[30]; <-- room for 29 characters + NUL terminating character
int age;
float salary;
}
struct details det1; <-- struct instance
然后,这个声明:
scanf("%s",&det1.empName);
需要改为:
scanf("%29s",det1.empName);
请注意,“%s”将在第一个“空白”处停止,因此员工姓名必须是单个单词
请注意,'%s' 总是将 NUL 字节附加到输入,因此 MAX CHARACTERS 修饰符必须比输入缓冲区的长度小 1。
你可以试试:
scanf( "%29[^\n], det1.empName );
因为这将读取输入,直到遇到 '\n' 或读取 29 个字符。
当然,对scanf()
代码的所有调用都应该检查返回值(而不是参数值)以确保操作成功。IE
if( scanf("%29s",det1.empName) != 1 )
{
// tell user about problem
fprintf( stderr, "scanf to read employee name failed\n" );
// cannot continue so exit program
// note: 'exit()' and EXIT_FAILURE
// are exposed via the statement:
// #include <stdlib.h>
exit( EXIT_FAILURE );
}
// implied else, scanf for employee name successful
因为scanf()
函数系列返回成功的“输入格式转换说明符”的数量(对于发布的代码中的所有三个调用scanf()
都期望返回值 1)
推荐阅读
- php - 如何使代码干燥而不重复,PHP
- rabbitmq - RabbitMQ 2 队列
- hazelcast - 使用谓词查询具有内部对象数组的 hazelcast 数据
- cypress - 赛普拉斯间谍在测试之间工作不一致
- javascript - 使用动态键减少对象数组
- java - 如何继续实施子菜单?Java 终端菜单
- go - 如何打印结构的 []byte 成员字符串
- sql - 如何使用 Microsoft Access 按日期获取最新记录
- javascript - 这个socket.io javascript示例如何翻译成打字稿
- esp32 - 使用 ESP32 和 Mongoose OS 检测按钮按下/GPIO 下拉