将字符串用户输入转换为 double

标签 c

我需要知道如何将用户输入(字符串)转换为 double 值。就像他在字符串“23.45”中写入一样,它会转换为 double 23.45 (没有任何库函数)。

我已经得到了整数代码,但不知道如何继续使用 double 代码:

#include <stdio.h>

void main()
{
    char input[100];
    printf("Type a String which will be converted to an Integer: ");
    scanf("%s", input);

    int number = 0;
    int i = 0;

    if (input[i] >= 48 && input[i] <= 57)
    {
        while (input[i] >= '0' && input[i] <= '9')
        {
            number = number * 10;
            number = number + input[i] - '0';
            i++;
        }
        printf("string %s -> number %d \n", input, number);
    }
    else
    {
        printf("Enter a number! \n");
    }
}

最佳答案

您可能没有理由推出自己的版本,因为 stdlib.h 中的 strtod 已经涵盖了所有格式。

这是一个包含带符号数字作为输入的版本,并且有一些提示可以放置更合适的错误处理:

#include <stdbool.h>

static void halt_and_catch_fire (void);

double strtod_homebrewn (const char* str)
{
  double result = 0;

  // handle signs:  
  bool is_negative = false;
  if(*str == '-')
  {
    is_negative = true;
    str++;
  }
  else if(*str == '+')
  {
    str++;
  }

  // handle the dot position:
  bool is_dot_found = false;
  double multiplier = 0.1;

  // the actual conversion:
  for(const char* s=str; *s!='\0'; s++)
  {
    if(*s >= '0' && *s <= '9') // ctype.h isdigit() would be preferred here
    {
      if(is_dot_found)
      {
        result += (*s - '0') * multiplier;
        multiplier /= 10;
      }
      else
      {
        result *= 10;
        result += *s - '0';
      }
    }
    else if(*s == '.')
    {
      if(is_dot_found) // two dots?
      {
        halt_and_catch_fire(); // replace this with error handling
      }

      is_dot_found = true;
    }
    else if(*s != '\0') // all cases tested, some weird unknown character found
    {
      halt_and_catch_fire(); // replace this with error handling
    }
  }


  if(is_negative)
  {
    result = -result;
  }

  return result;
}

static void halt_and_catch_fire (void)
{
  halt_and_catch_fire();
}

关于将字符串用户输入转换为 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858150/

相关文章:

c - C语言删除文件中的一行

c - C 编码阶段

c - 为什么不能修改在函数中作为 const 通过引用传递的地址之后的下一个地址的值?

c - 为什么我们在使用单指针传递给函数时必须对二维数组进行类型转换?

c - 如何使用 iso_c_binding 将 MPI 通信器句柄从 Fortran 传递到 C

c++ - 数组索引循环开始而不是内存访问错误

c - 在 Meteor Server 和 C app 之间建立 DDP 连接

c++ - 这里的typedef有什么用?

c - 读取 Linux 内核参数

c - 下面代码的执行顺序是什么?