简体   繁体   English

比较两个包含浮点值的字符串

[英]Compare two strings containing float values

I am given two strings which contain a floating point number. 我得到了两个包含浮点数的字符串。 I need to compare them. 我需要比较一下。 Can I directly compare the strings using std::string::compare and will this always give correct results? 我可以使用std::string::compare直接比较字符串,这将始终给出正确的结果吗? My current approach is to convert the string to float using std::stof , however I would prefer to avoid C++11 library functions. 我当前的方法是使用std::stof将字符串转换为float,但是我宁愿避免使用C ++ 11库函数。

simply comparing strings won't help you in cases like 仅仅比较字符串不会在以下情况下为您提供帮助

a = "0.43"
b = "0.4300"

if you need to compare first parse them into float and then compare them 如果需要比较,首先将它们解析为float,然后进行比较

std::string  s1  = "0.6"
std::wstring s2 = "0.7"
float d1  = std::stof(s1);
float d2 = std::stof(s2);

and then compare them 然后比较一下

here is a full program 这是一个完整的程序

#include <iostream>   // std::cout
#include <string>     // std::string, std::stof

int main ()
{
  std::string  s1  = "0.6"
  std::wstring s2 = "0.7"
  float d1  = std::stof(s1);
  float d2 = std::stof(s2);

  if(d1 == d2)
     std::cout << "Equals!";
  else
     std::cout << "Not Equals!";
  return 0;
}

click here for more reading on stof 单击此处以获取更多关于stof的信息

What about writing some ugly codes? 编写一些丑陋的代码呢? It may not be good practice but ... 这可能不是一个好习惯,但是...

int compare (const string &str1, const string &str2) {
    string *s1 = &str1, *s2 = &str2;
    int isReverse = 1;
    int len1, len2;

    if (str1.length() > str2.length()) {
        s1 = &str2;
        s2 = &str1;
        isReverse = -1;
    }

    len1 = s1->length();
    len2 = s2->length();

    if (!len1) {
        if (!len2))
            return 0;
        else if ((*s2)[0] != '-')
            return 1*isReverse;
        return -1*isReverse;
    }

    int i = 0;
    while(i < len1) {
        if ((*s1)[i] > (*s2)[i])
            return 1*isReverse;
        else if ((*s1)[i] < (*s2)[i])
            return -1*isReverse;
        i++;
    }

    while (i < len2) {
        if ((*s2)[i] != '0')
            return -1*isReverse;

        i++;
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM