Scanf检测前导0

扫码查看
本文介绍了Scanf检测前导0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何检测输入是否有前导零。

I would like to know how to detect if input got leading zeroes or not.

scanf("%d", &d);

这只会改变07到7等。

This will just change 07 to 7 etc..

最后我想返回(1)如果输入有前导零并且如果输入正常则返回(0)。

In the end i would like to return(1) if input got leading zeroes and return(0) if the input is ok.

谢谢。

推荐答案

如果您想知道数字是否有前导零,您必须将其作为字符串读取,并自行进行验证。字符串 07 只是表示性的,当存储为整数时,它只存储为 7

If you want to know if a number have leading zeros you have to read it as a string, and make the verification yourself. The string 07 is just presentational, when stored as an integer it's stored as just 7.

要验证您读取的字符串是带有前导零的整数,您可以先使用检查它确实是一个有效的整数。然后检查字符串中的第一个字符是否为'0'

To verify that the string you've read is an integer with leading zeros, you can first use strtol to check that it is indeed a valid integer. Then just check if the first character in the string is a '0'.

这篇关于Scanf检测前导0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 06:26
查看更多