【问题标题】:Why does my code does not work even though it is correct?为什么我的代码即使正确也不起作用?
【发布时间】:2020-01-22 01:57:56
【问题描述】:

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

}

【问题讨论】:

  • 代码不正确也能正常工作也是同理。:)
  • 此语句 scanf("%s",&det1.empName);产生未定义的行为。:)
  • 你真的没有得到任何警告吗?您是否告诉编译器生成它们? (-Wall -Wextra 用于 gcc 和 clang)
  • @Saumya Bhandari 而不是一个字符 char empName;你应该声明一个字符数组。
  • 我可以在那里发现几个问题,任何编译器都会至少给你警告,所以我不相信你的“它有 0 个错误和 0 个警告”的说法。

标签: c


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2020-02-20
    • 2022-11-14
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    相关资源
    最近更新 更多