获取存储为字符串的数字的小数部分

时间:2016-12-05 19:46:08

标签: c++ string stringstream ignore

我目前制作的程序要求我存储大的浮点数。我将它们存储为字符串,工作正常(当然我不得不重载我需要的一些操作符)(我不允许使用任何多精度算术库)。现在我正在寻找一种方法来获取数字的小数部分并将其存储为字符串。我想过使用stringstream并忽略,但这似乎并没有起作用。我的代码中有什么问题,因为它没有做任何事情吗?或者是否有其他方法来实现它(我还在考虑一个循环,它会遍历流直到一个点,这会起作用吗?)

string toDecimal(string x)
{
string decimalValue;
stringstream x2(x);
x2 >> x;
x2.ignore(100, '.'); //it can have up to 100 places before the dot
decimalValue = x2.str();
cout << decimalValue << end;
return decimalValue;
}

我想要实现的目标是:

 18432184831754814758755551223184764301982441

来自:

 18432184831754814758755551223184764301982441.4321432154

3 个答案:

答案 0 :(得分:3)

您还可以使用c++的{​​{1}}课程来完成此任务。以下代码演示了如何实现。

std::string

答案 1 :(得分:0)

不使用花哨的stringstream或其他任何东西,您只需使用:

char *x = "18432184831754814758755551223184764301982441.4321432154";
char *p = x;
while (*p != '.' && *p != 0)
    p++;
*p = 0;
// now x holds the string until the .

答案 2 :(得分:0)

你的方法是完全有效的(我知道你的方法是删除字符串的小数部分,但这不是你的代码所做的)。在复杂性方面,我认为不能添加太多,因为你不能在不进行线性扫描的情况下神奇地发现点的位置。这意味着你的想法在算法本身方面已经足够好了。我认为msrd0的答案在执行方面会更有效,因为它使用低级纯C实现。但我认为Emmanuel是最好的答案,因为它更简单,更容易维护。但是如果你坚持要做与你试图做的事情类似的事情,或者如果你真的需要使用stringstream ,那么我就有了这个代码的工作版本。

#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>

std::string toDecimal(std::string x){
    std::string decimalValue;
    std::reverse(x.begin(), x.end());
    std::stringstream x2(x);
    x2.ignore(100, '.'); 
    x2 >> decimalValue;
    std::reverse(decimalValue.begin(), decimalValue.end());
    std::cout << decimalValue << std::endl;
    return decimalValue;
}

Ps:此代码假定您在字符串中有一个点。