2017-02-28 56 views
2

我有一个包含由空格分隔的十六进制值的文件。我想查找每个十六进制值的频率并将其写入文本文件。例如,考虑字符串"1b 17 3c 45 3f 52 7a 5a 3b 45 31 52 2e 17 3e 58 3f 44 "。我要统计每个十六进制值出现的频率:计算.txt文件中的十六进制字符的频率

1b - 1 times 
17 - 2 times 
.... so on. 

我当前已写了一个C++程序,但它算作一个十六进制字符的十六进制字符之间的空间,以及和没有按预期发挥作用。

#include <iostream> 
#include <fstream> 
#include <string> 
#include <iomanip> 

using namespace std; 

int main() 
{ 
    int x = 0; 
    int total[128] = {0}; 
    int index; 

    ifstream infile; 
    ofstream outfile; 

    infile.open("hex.txt"); 
    outfile.open("results2.txt"); 
    if(!infile) 
    { 
     cout << "Error opening input file" << endl; 
     return 0; 
    } 

    char c; 
    while(infile.get(c)) 
    { 
     index = c; 
     total[index]++; 
    } 

    for (int i=0; i<128; i++)  // Print the results 
    { 
     outfile << " " << hex << i << " occurs " 
       << setw(5) << dec << total[i] << " times" 
       << " " << endl; 
    } 
    return 0; 
} 

注:

"hex.txt" is the input file 
"results2.txt" is the output file 
+0

阅读[问],然后按照建议。并且不要垃圾邮件标签。 C和C++是** Disctinct **语言! – Olaf

+0

你的问题是什么?你自己有多远? – Aeonos

+3

使用[map](http://en.cppreference.com/w/cpp/container/map)。 – BLUEPIXY

回答

2

只需读取输入文件为十六进制:

while(infile >> hex >> index) 
{ 
    if (index < 0 || index >= 128) { // ensure value is in array range... 
     cerr << "Found an incorrect value " << hex << index << endl; 
     return 1; 
    } 
    total[index]++; 
} 
+0

谢谢@Serge。此方法有效 –