user3678290 user3678290 - 24 days ago 13
C++ Question

reading a hex column from input file

heres a sample of the file: it has two columns, the second one is a hex value

0 298478
0 298478
2 3636
0 70f60874

...

im trying to put the first column in a vector and second column in another vector, ive tried multiple things but it either stops after it reaches 'f' in the fourth line of the input file or gives me weird values when accessing the vectors.

using namespace std;

int main()
{
vector <int> label;
vector <int> address;

ifstream ifile("data.txt");

if (!ifile.is_open())
{
cout << "Error opening file\n";
}

while (!ifile.eof())
{

int a;
long long b;
ifile >> a >> hex >> b;
if (ifile.fail())
{
break;
}
label.push_back(a);
address.push_back(b);

}

cout << label[3] << "\n";
cout << address[3];

}


when i run this i get:
0
1895172212

if i run it without "hex >> b" i get accurate results but it wont get past the 'f' in line 4. Please im new to this and i appreciate any help

Answer

1895172212 is actually the correct value (when converting 70f60874 to decimal), in other words - you are printing the value as decimal, if you want to print it as a hexadecimal value you need use hex for your output as well.

Comments