Representing big numbers in source code for readability?

后端 未结 5 2106
难免孤独
难免孤独 2020-11-27 23:23

Is there a more human-readable way for representing big numbers in the source code of an application written in C++ or C?

let\'s for example take the number 2,

5条回答
  •  情书的邮戳
    2020-11-28 00:10

    With a current compiler (C++14 or newer), you can use apostrophes, like:

    auto a = 1'234'567;
    

    If you're still stuck with C++11, you could use a user-defined literal to support something like: int i = "1_000_000"_i. The code would look something like this:

    #include 
    #include 
    #include 
    
    int operator "" _i (char const *in, size_t len) { 
        std::string input(in, len);
        int pos;
    
        while (std::string::npos != (pos=input.find_first_of("_,"))) 
            input.erase(pos, 1);
    
        return std::strtol(input.c_str(), NULL, 10);
    }
    
    int main() { 
        std::cout << "1_000_000_000"_i;
    }
    

    As I've written it, this supports underscores or commas interchangeably, so you could use one or the other, or both. For example, "1,000_000" would turn out as 1000000.

    Of course, Europeans would probably prefer "." instead of "," -- if so, feel free to modify as you see fit.

提交回复
热议问题