从文件中读取十六进制数

时间:2011-07-21 12:42:45

标签: c++

这让我感到非常困扰,因为我应该能够做到这一点,但是当我读取十六进制数并在打印出来时将其分配给unsigned int时,我会得到一个不同的数字。任何建议都会很棒。感谢

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
fstream myfile;
myfile.open("test.text");
unsigned int tester;
string test;
myfile >> hex >> tester;
cout << tester;
system("pause");
return 0;
}

2 个答案:

答案 0 :(得分:1)

我打赌你没有得到“不同的号码”。

我打赌你得到相同的值,但是用十进制表示。

您已经在提取十六进制表示值(myfile >> hex >> tester);现在也插入一个(cout << hex << tester)!

答案 1 :(得分:0)

这适用于字符串格式的十六进制值到int

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    fstream myfile;
    myfile.open("test.txt");
    string fromFile;
    unsigned int tester;

    myfile >> fromFile;
    istringstream iss(fromFile);
    iss >> hex >> tester;
    cout << tester;

    system("pause");
    return 0;
}

这适用于int到hex

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
fstream myfile;
myfile.open("test.txt");
unsigned int tester;
string test;
myfile >> tester;
cout << hex << tester;

system("pause");
return 0;
}

同时检查您的文件名。在我的文件中,它上面写着54,而输出是十六进制中的36。

相关问题