I want to read an number of integers from a .txt file. The file is composed of three columns of numbers each separated by a space. So it's formatted as follows:
I'm not sure how to read in integers from a file? I can read strings but I can't find anything that deals with these (hexadecimal numbers).
I need to read in the first number, identify the whitespace as the end of it and then read the next number on the line until a whitespace if found and then read the last number in if it exists (it will only be there if the number in the first column is a 1).
I've not tested this, but it should give you an idea.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <string>
#include <cstdio>
int main()
{
string line = "1 0x00000010 0x0000000A"int int1, int2, int3;
//using sscanf no because i'm using a string, scanf is for streams
//=scan string "line" for format "decimal<space>hex<space>hex" and put results in the following variables
sscanf(line, "%d %x %x", &int1, &int2, &int3);
cout << int1 << " " << int2 << " " << int3;
return 0;
}
The basic idea is that you can tell the extraction operator (>>) what kind of integer representation you want you use (e.g., dec, bin, oct ...) to read in a particular value.
std::ifstream file( "whatever.txt" ) ;
std::string line ;
while( std::getline( file, line ) )
{
std::istringstream stm(line) ;
int i, j, k ;
if( stm >> std::dec >> i >> std::hex >> j && ( i==1 ? stm >> k : !( k = 0 ) ) )
{
// use i, j, and if i==1, k
}
else /* error */ break ;
}
NwN I've tried it but get an error which reads
error C2664: 'sscanf' : cannot convert parameter 1 from 'std::string' to 'const char *'
Am I right in thinking this is because the numbers are defined in a string, called line, but when I call sscanf I'm looking for a decimal value and then a hexadecimal?
sscanf takes a C-style string as it's argument, and the C++ strings are class objects. So when you try to use std::string as the argument, sscanf gets confused and decides to quit. (Not the technically correct answer, but the same idea :-)
JLBorges / astropos 's idea are probably better here, I'd go for that.
Could either one of you perhaps be so kind as to explain why you prefer this method?
Is it because it directly acts on the stream and is consequently much faster than using a function to traverse the file?