Legge una stringa intera a 64 bit dal file
Domanda
Abbiamo un file che contiene un numero intero a 64 bit come stringa. Come possiamo scanf () o altrimenti analizzare questa stringa numerica in un tipo intero a 64 bit senza segno in C ++?
Siamo a conoscenza di cose come% lld ecc., ma molti modi per eseguire questa analisi sembrano interrompere le compilazioni in diversi compilatori e stdlibs. Il codice dovrebbe essere compilato sotto gcc e il compilatore Microsoft C ++ (ovviamente la piena conformità agli standard sarebbe un vantaggio)
Soluzione
GCC ha molto tempo, così come i compilatori per C ++ 0x. MSVC ++ non (ancora), ma ha il suo __int64 che puoi usare.
#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;
Altri suggerimenti
Alnitak consiglia strtoull ()
, ma sembra che non sia disponibile in ambienti Win32 . Il thread del forum collegato al link raccomanda di sostituire _strtoui64 ()
, _wcstoui64 ()
e _tcstoui64 ()
. Forse questo è "al limite" di cose che non possono essere realmente eseguite con una singola chiamata di funzione portatile e potrebbe essere necessario implementare percorsi di codice diversi per piattaforme diverse. Oppure, immagino, scrivi il tuo convertitore da ASCII a 64 bit, non è scienza missilistica.
O usa la sicurezza tipica di 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;
Non usare scanf ()
, tokenizzare i tuoi input separatamente e quindi usare strtoull ()
o simile.