Read 64 bit integer string from file

2019-07-03 21:56发布

We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ?

We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should compile under gcc and the Microsoft C++ compiler (of course full compliance with standards would be a plus)

5条回答
闹够了就滚
2楼-- · 2019-07-03 22:26

Don't use scanf(), tokenize your input separately and then use strtoull() or similar.

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-03 22:36
std::fstream fstm( "file.txt" );
__int64 foo;
fstm >> foo;
查看更多
叼着烟拽天下
4楼-- · 2019-07-03 22:42

GCC has long long, as will compilers for C++0x. MSVC++ doesn't (yet), but does have its __int64 you can use.

#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;
查看更多
forever°为你锁心
5楼-- · 2019-07-03 22:42

Alnitak recommends strtoull(), but it seems it's not available in Win32 environments. The linked-to forum thread recommends either of _strtoui64(), _wcstoui64() and _tcstoui64() as replacements. Perhaps this is "on the edge" of stuff that can't really be done with a single portable function call, and you might need to implement different code paths for different platforms. Or, I guess, write your own ASCII-to-64-bit converter, it's not rocket science.

查看更多
走好不送
6楼-- · 2019-07-03 22:46

Or use the typesafety of 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;
查看更多
登录 后发表回答