C:使用 scanf() 函数而不是 gets

标签 c string shell

/* hexadecimal to decimal conversion */

#include <stdio.h>
#include <math.h>
#include <string.h>

int main()
{
 char hex[17];
 long long decimal;
 int i , val, len;
 decimal = 0;


 // Input hexadecimal number from user

 printf("Enter any hexadecimal number: ");
 gets(hex);
 //Find the length of total number of hex digit
 len = strlen(hex);
 len--;

 for(i=0; hex[i]!='\0'; i++)
 {
 // Find the decimal representation of hex[i]
 if(hex[i]>='0' && hex[i]<='9')
 {
  val = hex[i] - 48;
 }
 else if(hex[i]>='a' && hex[i]<='f')
 {
  val = hex[i] - 97 + 10;
 }
 else if(hex[i]>='A' && hex[i]<='F')
 {
  val = hex[i] - 65 + 10;
 }
 decimal += val * pow(16, len);
 len--;
 }
 printf("Hexadecimal number = %s\n", hex);
 printf("Decimal number = %lld", decimal);
 return 0;
}

在上面的程序中,当我使用 scanf 而不是 gets 时,它没有给出结果。为什么?我使用了 scanf("%x",hex); 。请解释一下 decimal += val * pow(16, len);。提前非常感谢。

最佳答案

因为如果您使用 scanf(),它会为您完成字符串转换,这就是它的全部要点。

unsigned int x;
if(scanf("%x", &x) == 1)
  printf("you entered %d (hex 0x%x)\n", x, x);

您不能将 %x 指针组合到字符数组,它需要一个指向无符号整数的指针。这当然在 manual page 中有详细记录。

此外,在这里使用 pow() 似乎有点多余,只需将您所拥有的值乘以 16然后添加每个新数字即可:

unsigned int parsehex(const char *s)
{
  unsigned int x = 0;
  const char *digits = "0123456789abcdef";
  const char *p;
  while(*s && (p = strchr(digits, tolower(*s++))) != NULL)
  {
    x *= 16;
    x += (unsigned int) (p - digits);
  }
  return x;
}

这比您的代码“重”一点(使用 strchr()),但更短,因此可能更容易验证。如果它对性能过于关键,我会考虑研究它。

关于C:使用 scanf() 函数而不是 gets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43003074/

相关文章:

php - PHP 中检查值是否为 MySQL 日期时间格式的快速方法?

php - 在php中获取字符串中逗号字符之间的数字

c# - 找出有多少字符串匹配

linux - 如何在Linux shell中循环相同格式的文件

linux - 如何获取文件名(从另一个文件)作为 cp linux 脚本的参数

apache - 如何从网络服务器调用本地 shell 脚本?

c - 像 strtok() 这样的程序,用于两个分隔符

我可以轻松地更改从 C 程序输出到 Windows 控制台的文本颜色吗

python - 什么更快 : multiple `send` s or using buffering?

c - Sandy Bridge 上的 32 字节存储转发