首页 > 解决方案 > 为什么我的代码即使正确也不起作用?

问题描述

这是我的代码的一部分。它有 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);

}

标签: c

解决方案


关于 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)


推荐阅读