【问题标题】:Getting the decimal part of a number stored as string获取存储为字符串的数字的小数部分
【发布时间】:2026-01-04 14:30:01
【问题描述】:

我目前正在制作的程序需要我存储大量的浮点数。我将它们存储为字符串,它工作正常(当然我不得不重载一些我需要的运算符)(我不允许使用任何多精度算术库)。现在我正在寻找一种方法来获取数字的小数部分并将其存储为字符串。我考虑过使用 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

【问题讨论】:

  • 所以你想获取从开始到第一个点的子字符串?您可以使用std::string::find 查找点,然后使用std::string::substr 获取从开始到点位置的子字符串。
  • 请注意,. 的左侧通常是整数部分,. 的左侧是小数部分。对于其中任何一个,只需使用finderase 删除您不想要的部分。
  • @NathanOliver 听起来不太对 ;)

标签: c++ string stringstream


【解决方案1】:

您也可以使用c++std::string 类来完成此操作。以下代码演示了如何实现。

std::string toDecimal(std::string x)
{
    return s.substr(0, s.find("."));
}

【讨论】:

    【解决方案2】:

    您的方法完全有效(我知道您的方法是删除字符串的小数部分,但这不是您的代码所做的)。考虑到复杂性,我认为不能添加太多内容,因为如果不进行线性扫描,您将无法神奇地发现点的位置。这意味着您的想法就算法本身而言已经足够好了。我认为 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:此代码假定您在字符串中确实有一个点。

    【讨论】:

      【解决方案3】:

      不使用花哨的stringstream 或其他什么,您可以简单地使用:

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

      【讨论】:

      • @AndreaGrillo 你能告诉我为什么你认为p++ 而不是*p=0 在这种情况下会这样做吗?对我来说,似乎什么都不做,而且在 . 之前绝对不会持有字符串