我正在制作一个霍夫曼编码器,为此我需要读取输入(始终是重定向文件)以记录频率,然后创建代码本,然后再次读取输入,以便我可以对其进行编码。
我的问题是我目前正在尝试测试如何使文件从 cin 读取两次。
我在网上读到 cin.seekg(0) 或 cin.seekg(ios::beg) 或 cin.seekg(0, ios::beg) 只要文件被重定向而不是管道,都应该工作得很好。但是当我这样做时,它似乎对cin的位置没有任何作用。
这是我目前正在使用的代码:
#include<iostream>
#include"huffmanNode.h"
using namespace std;
int main(){
//create array that stores each character and it's frequency
unsigned int frequencies[255];
//initialize to zero
for(int i=0; i<255; i++){
frequencies[i] = 0;
}
//get input and increment the frequency of corresponding character
char c;
while(!cin.eof()){
cin.get(c);
frequencies[c]++;
}
//create initial leafe nodes for all characters that have appeared at least once
for(int i=0; i<255; i++){
if(frequencies[i] != 0){
huffmanNode* tempNode = new huffmanNode(i, frequencies[i]);
}
}
// test readout of the frequency list
for(int i=0; i<255; i++){
cout << "Character: " << (char)i << " Frequency: " << frequencies[i] << endl;;
}
//go back to beginning of input
cin.seekg(ios::beg);
//read over input again, incrementing frequencies. Should result in double the amount of frequencies
**THIS IS WHERE IT LOOPS FOREVER**
while(!cin.eof()){
cin.get(c);
frequencies[c]++;
}
//another test readout of the frequency list
for(int i=0; i<255; i++){
cout << "Character: " << (char)i << " Double Frequency: " << frequencies[i] << endl;
}
return 0;
}
调试显示它卡在第 40 行的 while 循环中,并且似乎不断获得换行符。为什么它不退出这个循环?我假设 cin.seekg() 实际上并没有重置输入。