一个字符串转换为双 [英] converting a string into a double

查看:177
本文介绍了一个字符串转换为双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一种方式来获得浮动从用户角度输入。

I am looking for a way to get floating point input from a user.

我要去这个方法是使用一个自制getstrn功能,并把它插入到这将字符串转换成一个双另一个函数。

My way of going about this is to use a self-made getstrn function and plug that into another function which would convert the string into a double.

我安全的GET字符串:

My safe get string:

void safeGetString(char arr[], int limit){
    int c, i;
    i = 0;
    c = getchar();
    while (c != '\n'){
        if (i < limit -1){
            arr[i] = c;
            i++;
        }
        c = getchar();
    }
    arr[i] = '\0';
}

什么是写这个get_double功能的最佳方式?

What would be the best way to write this get_double function?

推荐答案

尝试的strtod功能:

Try the strtod function:

char *end;
double num = strtod(arr, &end);

本月底将被处理的最后一个字符后点。您可以设置第二个 NULL ,如果你不关心这个。或者你可以使用 ATOF ATOF(STR)等同于的strtod(STR( CHAR **)NULL)

The end will point after the last char that was processed. You can set the second to NULL if you don't care about that. Or you can use atof: atof(str) is equivalent to strtod(str, (char **)NULL).

但是,你应该小心,因为你可以检查输入的格式不正确:

But you should care, since you can check if the input is malformed:

if (*end != '\0')
  // Handle malformed input

这篇关于一个字符串转换为双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆