简体   繁体   English

为什么我输入错误的数据类型时我的c程序不会崩溃

[英]why my c program doesn't crash when i entered the wrong data type

I'm new to c and I'm writing a basic program that ask the user for input 我是c语言的新手,正在编写一个基本程序,要求用户输入

#include <stdio.h>

int main(void){
    float weight;
    printf("enter your weight in kg:\n");
    fflush(stdout);
    scanf("%f", &weight);
    printf("your weight is %f kg\n", weight);
    return 0;
}

Everything works as expected when I under a number when asked for input. 当我要求输入数字时,一切正常。 But when I accidentally entered words, the program doesn't crash and instead print out your weight is 0.00000 kg . 但是当我不小心输入了单词时,程序不会崩溃,而是打印出your weight is 0.00000 kg

I was just wondering, why doesn't my program crash when it expect numbers but I have entered words? 我只是想知道,为什么我的程序在期望输入数字但没有输入数字时会崩溃? and why did it printed out 0.00000 ? 为什么打印了0.00000

why my c program doesn't crash when i entered the wrong data type 为什么我输入错误的数据类型时我的c程序不会崩溃

When a user of your program enters some input that can't be converted by scanf to a float, the variable weight will not be initialized. 当程序的用户输入某些不能由scanf转换为float的输入时,可变weight将不会初始化。 So when the program prints the variable, it will read an uninitialized float. 因此,当程序打印变量时,它将读取未初始化的浮点数。 According to the c standard, that has undefined behavior. 根据c标准,具有未定义的行为。

However, undefined behavior does not guarantee a program crash. 但是,未定义的行为不能保证程序崩溃。 It may crash or it may continue execution. 它可能会崩溃或可能继续执行。 We can't know as it is undefined what will happen. 我们不知道会发生什么,因为尚不确定。 On your system execution just continued but on another system a program may happen. 在您的系统上执行只是继续,但是在另一个系统上可能会发生程序。

On many systems the memory allocated to a program as startup is initialized to all zeros. 在许多系统上,启动时分配给程序的内存被初始化为全零。 Therefore variables in main is (often) an all zero binary pattern when left uninitialized. 因此, main变量在未初始化时通常是全零的二进制模式。 For floats that translate to the value 0.0 对于转换为值0.0

So even if you don't initialize weight it seems as if it was initialized to zero and your program runs fine even with input like abc and prints the weight as 0.0 因此,即使您不初始化weight它似乎也已初始化为零,并且即使输入了abc这样的程序也可以正常运行,并将权重显示为0.0

However, from a standard point of view it is still undefined behavior to read an uninitialized float variable 但是,从标准的角度来看,读取未初始化的float变量仍然是未定义的行为

If you did the same inside a function that you called a number of times (with other function calls in between), you would see strange behavior sooner or later. 如果您在多次调用的函数中执行了相同的操作(之间又调用了其他函数),则迟早会看到奇怪的行为。 Typically just a print of strange values but on some systems, you might see a crash (but that is more rare). 通常,它只是打印出奇怪的值,但是在某些系统上,您可能会看到崩溃(但这很少见)。

You should do: 你应该做:

if (scanf("%f", &weight) == 1)
    printf("your weight is %f kg\n", weight);
else
    printf("Illegal input\n");

Every input the user gives in C is treated as a string, though the input you provide is in numbers. 用户在C中提供的每个输入都被视为字符串,尽管您提供的输入是数字。 After getting the input from the user, it is converted in to numeric data using atoi (ascii to integer) function ( man atoi ). 从用户那里获得输入后,使用atoi(ascii到整数)函数( man atoi )将其转换为数字数据。 The return value of this function is the converted value. 该函数的返回值是转换后的值。 Upon successfully converting the given string to an integer it returns the converted integer value and it returns zero when the resultant value is a non-integer. 成功将给定的字符串转换为整数后,它将返回转换后的整数值,当结果值是非整数时则返回零。 This is the reason why it is not showing any error when you input different data. 这就是为什么当您输入其他数据时它没有显示任何错误的原因。

Try the same code with different format specifiers, so that you can have a clear understanding. 使用不同的格式说明符尝试相同的代码,以便您可以清楚地了解。

The MAN page of scanf : scanf

Return Value 返回值

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure. 这些函数返回成功匹配和分配的输入项的数量,该数量可能少于所提供的数量,在早期匹配失败的情况下甚至为零。

So, scanf return the number of arguments successfully scanned. 因此, scanf返回成功扫描的参数数量。 that's why your program not crashing. 这就是为什么您的程序不会崩溃的原因。

the program does not crash because the input does nothing to cause a crash. 程序不会崩溃,因为输入不会导致崩溃。

However, the posted code does have a major flaw. 但是,发布的代码确实存在重大缺陷。 This line: 这行:

scanf("%f", &weight);

should be: 应该:

if( 1 != scanf("%f", &weight) )
{
    perror( "scanf failed" );
    exit( EXIT_FAILURE );
}

// implied else, scanf successful

In other words, always check system functions for errors, especially those that are performing input. 换句话说,请始终检查系统功能是否存在错误,尤其是正在执行输入的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么当我写到数组末尾时我的程序不会崩溃? - Why doesn't my program crash when I write past the end of an array? 当我分配错误的内存量时,为什么C不会崩溃 - Why doesn't C crash when I malloc wrong amount of memory 为什么当我溢出分配的字符数组时,我的C程序不会崩溃? - How come my C program doesn't crash when I overflow an allocated array of characters? 我的程序没有 output 我输入的第一个值在我的数组中搜索。 为什么? - My program doesn't output the first value I entered to search in my array. Why? 为什么当我按0时程序没有停止? C程序 - Why doesn't my program stop when I press 0? C program 当我尝试重新分配()结构指针数组时,为什么我的 C 程序会崩溃? - Why does my C program crash when I try to realloc() a pointer array of structs? 当我尝试从单链表中删除节点时,为什么我的 C 程序崩溃 - Why does my C Program crash when I try to delete a node out of a singe linked list 为什么当我向 main 函数添加任何语句时,我的 C 程序会崩溃? - Why does my C program crash when i add any statement to the main function? 为什么这个C程序不能编译?这有什么问题? - Why doesn't this C program compile? What is wrong with this? 为什么这个 c 程序在输入 0 时没有结束? - Why does this c program not end when entered 0?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM