为什么我的代码即使正确也不能正常工作?

时间:2020-01-22 01:57:56

标签: 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);

}

1 个答案:

答案 0 :(得分:0)

关于OP的发布代码:

通过启用了最有用警告的编译器运行它会导致:

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()的调用,代码都应检查返回的值(而不是参数值),以确保操作成功。 I.E。

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)