【问题标题】:Read 64 bit integer string from file从文件中读取 64 位整数字符串
【发布时间】:2008-10-31 09:32:59
【问题描述】:

我们有一个文件,其中包含一个 64 位整数作为字符串。我们如何 scanf() 或以其他方式将此数字字符串解析为 C++ 中的无符号 64 位整数类型?

我们知道诸如 %lld 之类的东西,但是执行此解析的许多方法似乎会破坏不同编译器和标准库下的编译。代码应在 gcc 和 Microsoft C++ 编译器下编译(当然完全符合标准将是一个加分项)

【问题讨论】:

    标签: c++ parsing 64-bit integer


    【解决方案1】:

    GCC 有很长的历史,C++0x 的编译器也有很长的历史。 MSVC++(还没有),但确实有它的 __int64 你可以使用。

    #if (__cplusplus > 199711L) || defined(__GNUG__)
        typedef unsigned long long uint_64_t;
    #elif defined(_MSC_VER) || defined(__BORLANDC__) 
        typedef unsigned __int64 uint_64_t;
    #else
    #error "Please define uint_64_t"
    #endif
    
    uint_64_t foo;
    
    std::fstream fstm( "file.txt" );
    fstm >> foo;
    

    【讨论】:

    • 就个人而言,我会使用 stdint.h 中的 uint64_t。它是 C99 标准,而不是 C++,但它在 GCC 中,您可以轻松地在线找到 VC++ 版本并将它们放入您的项目中。未来 J. Random 平台也是如此,如果幸运的话,它会在 C++0x 中。
    • 它在 C++0x 中。尽管 (u)int64_t 实际上是可选的,但可以放心地假设它可用于 PC。否则,可以使用 uint_least64_t 或 uint_fast64_t。
    【解决方案2】:

    Alnitak 推荐strtoull(),但似乎不是available in Win32 环境。链接到的论坛主题推荐_strtoui64()_wcstoui64()_tcstoui64() 作为替代品。也许这是无法通过单个可移植函数调用真正完成的事情的“边缘”,您可能需要为不同的平台实现不同的代码路径。或者,我想,写你自己的 ASCII 到 64 位转换器,这不是火箭科学。

    【讨论】:

      【解决方案3】:

      或者使用 istream 的类型安全...

        using namespace std;
      
        // construct a number -- generate test data
        long long llOut = 0x1000000000000000;
        stringstream sout;
        // write the number
        sout << llOut;
        string snumber = sout.str();
        // construct an istream containing a number
        stringstream sin( snumber );
      
        // read the number -- the crucial bit
        long long llIn(0);
        sin >> llIn;
      

      【讨论】:

        【解决方案4】:
        std::fstream fstm( "file.txt" );
        __int64 foo;
        fstm >> foo;
        

        【讨论】:

          【解决方案5】:

          不要使用scanf(),单独标记您的输入,然后使用strtoull() 或类似名称。

          【讨论】:

          • Windows 原生支持 strtoull() 吗?
          • 你可以很容易地自己制作。
          • 公平地说,我确实说过“或类似的”:)
          猜你喜欢
          • 1970-01-01
          • 2019-05-12
          • 1970-01-01
          • 2017-05-03
          • 2023-04-09
          • 2016-08-09
          • 2012-01-03
          • 1970-01-01
          • 2012-07-17
          相关资源
          最近更新 更多