Reputation: 342
How to store a file to unsigned int
#include <iostream>
#include <fstream>
using namespace std;
unsigned int key[4];
int main(){
ifstream file("key.txt");
store(file);
return 0;
}
I have this data in my key.txt
0xFDA5
0xD54E
0xFC00
0xB55A
I created this function
void store(ifstream &file){
int i = 0;
if(!file)
cout << "Couldn't open file " << endl;
while(!file.eof()){
file >> hex >> key[i];
i++;
}
for( int i = 0 ; i < 4 ; i++ ){
cout << k[i] << endl;
}
}
I get the number is in hex value . My question is if I want to get back this output
0xFDA5
0xD54E
0xFC00
0xB55A
which code should I use?
Upvotes: 0
Views: 114
Reputation: 96
As said before, std::hex
for hexadecimal, std::showbase
for the 'Ox' prefix and std::uppercase
for the uppercase.
But what about simply using the STL instead of the for
loop :
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iterator>
int main()
{
std::ifstream file("key.txt");
copy(
std::istream_iterator<unsigned int>(file>>std::hex)
,std::istream_iterator<unsigned int>()
,std::ostream_iterator<unsigned int>(std::cout<<std::hex<<std::uppercase<<std::showbase,"\n")
);
return 0;
}
Even if you need a variable to store items :
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream file("key.txt");
std::vector<unsigned int> keys;
keys.reserve(4);
copy(
std::istream_iterator<unsigned int>(file>>std::hex)
,std::istream_iterator<unsigned int>()
,back_inserter(keys)
);
copy(
begin(keys)
,end(keys)
,std::ostream_iterator<unsigned int>(std::cout<<std::hex<<std::uppercase<<std::showbase,"\n")
);
return 0;
}
Upvotes: 0
Reputation: 595
For uppercase output (e.g. 0XFDA5) edit the for
loop as follows:
for( int i = 0; i < 4; i++ ) {
cout << std::uppercase << showbase << std::hex << key[i] << endl;
}
or
for( int i = 0; i < 4; i++ ){
printf("%#X\n", key[i]);
}
For lowercase output(e.g. 0xfda5) edit the for
loop as follows:
for( int i = 0; i < 4; i++ ) {
cout << showbase << std::hex << key[i] << endl;
}
or
for( int i = 0; i < 4; i++ ){
printf("%#x\n", key[i]);
}
Upvotes: 2