使用strtol在c ++中获得long double

时间:2015-03-06 19:56:04

标签: c++ arrays strtol long-double

我想从数组中获取long double。

long double num;  
char * pEnd;  
char line[] = {5,0,2,5,2,2,5,4,5,.,5,6,6};  
num = strtold(line1, &pEnd);  

出于某种原因,我得到的数字四舍五入为502522545.6 我对C ++很陌生,所以我做错了吗?需要做些什么来获取num中的整数而不是舍入?

感谢您的帮助!!!

很抱歉这是我在这里的第一篇帖子=)

所以整个程序代码如下:

class Number  
{  
private:

    long double num ;
    char line[19], line2[19]; 
    int i, k;
public:

    Number()
    {}

    void getData()
    {
        i = 0;
        char ch= 'a';
        cout << "\nPlease provide me with the number: ";
        while ((ch = _getche()) != '\r')
        {
            line[i] = ch;
            line2[i] = ch;
            i++;
        }
    }
    void printData() const
    {
        cout << endl;
        cout << "Printing like an Array: ";
        for (int j = 0; j < i; j++)
        {
            cout << line[j];
        }
        cout << "\nModified Array is: ";
        for (int j = 0; j < (i-k); j++)
        {
            cout << line2[j];
        }
        cout << "\nTHe long Double is: " << num;

    }
    void getLong()
    {
        char * pEnd;
        k = 1;
        for (int j = 0; j < i; j++)
        {
            if (line2[j+k] == ',')
            {
                k++;
                line2[j] = line2[j + k];
            }
            line2[j] = line2[j + k];
        }
        line2[i -k] = line2[19];
        num = strtold(line2, &pEnd);
    }
};

int main()  
{  
    Number num;  
    char ch = 'a';  
    while (ch != 'n')  
    {  
        num.getData();  
        num.getLong();  
        num.printData();  
        cout << "\nWould you like to enter another number ? (y/n)";  
        cin >> ch;   
    }  
    return 0;  
}

输入的数字是以下格式($ 50,555,355.67)或任何其他数字。程序然后删除数字和“。”的所有符号。 然后我试图从数组中获取长双数。 如果你运行该程序,你总是从num。

获得四舍五入的数字

3 个答案:

答案 0 :(得分:3)

C ++的做法非常简单:

#include <sstream>
#include <iostream>
#include <iomanip>

int main() {
  const std::string line = "502522545.566";  
  long double num;  

  std::istringstream s(line);

  s >> num;

  std::cout << std::fixed << std::setprecision(1) << num << std::endl;
}

答案 1 :(得分:2)

使用现代C ++,你可以做到:

auto line = "502522545.566"s;

auto num = std::stold(line);

Live example

答案 2 :(得分:0)

Theres可能是更多的C ++方式,但sscanf会起作用:

const char *str = "3.1459";
long double f;
sscanf(str, "%Lf", &f);