Read 64 bit integer string from file

亡梦爱人 提交于 2020-01-04 05:06:15

问题


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)


回答1:


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;



回答2:


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.




回答3:


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;



回答4:


std::fstream fstm( "file.txt" );
__int64 foo;
fstm >> foo;



回答5:


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



来源:https://stackoverflow.com/questions/252962/read-64-bit-integer-string-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!