我们有一个文件,其中包含一个64位整数的字符串。在C++中,如何使用scanf()或其他方法将此数字字符串解析为无符号64位整数类型?
我们知道像%lld等方式,但许多解析方法似乎会在不同编译器和stdlib下出现编译错误。代码应该在gcc和Microsoft C ++编译器下编译(当然,完全符合标准将是一个加分项)。
GCC已经支持long long,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;
Alnitak建议使用strtoull()
,但似乎在Win32环境中不可用。链接到的论坛帖子建议使用_strtoui64()
、_wcstoui64()
和_tcstoui64()
中的任意一个作为替代方案。也许这是一些不能通过单个可移植函数调用完成的东西的边缘,你可能需要为不同平台实现不同的代码路径。或者,我猜,编写自己的ASCII-to-64位转换器,这并不是什么高深的科学。
或者利用 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;
std::fstream fstm( "file.txt" );
__int64 foo;
fstm >> foo;
scanf()
,请将输入分词后再使用strtoull()
或类似函数。