我不能工作了如何從一個文件,而不是從的getchar()的字符串的獲得字符,而不是的getchar
計算熵閱讀文本
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include <string>
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstring>
using namespace std;
double log2(double number)
{
return log(number)/std::log(2.);
}
int main() {
unsigned long table[256], total = 0;
double entropy = 0;
char mychar;
string line;
ifstream myfile ("sometext.txt");
if (myfile.is_open())
{
while (getline (myfile,line))
{
cout << line << '\n';
}
}
short i;
for(i=0; i<256; i++)
table[i] = 0;
while(1)
{
mychar = getchar();
如何從閱讀的myfile.txt ?
與std::getline()
if (mychar==EOF) // ctrl Z
{break;}
table[mychar]++;
}
for(i=33;i<127;i++)
if(table[i]) {
total += table[i];
entropy -= log2(table[i])*table[i];
}
entropy /= total;
entropy += log2(total);
printf("Total Characters: %6d\n",total);
printf("Entropy: %5.6f\n",entropy);
}
從問題中的代碼判斷,不妨讀取和打印這些行,但是從行中而不是文件再次獲取字符,並手動添加新行。儘管如此,這絕對是很好的知識。 – chris
@chris:好點!我更新了答案,提到可以立即使用這些行。 –
好主意 - 但是究竟如何從印刷的線條中取出字符? – James