2014-01-07 35 views
0

我不能工作了如何從一個文件,而不是從的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); 
} 

回答

2

循環讀取線讀取文件的內容!字符串line

while (std::getline(myfile, line)) { 
    std::cout << line << '\n'; 

    for (std::string::const_iterator it(line.begin()), end(line.end()); it != end; ++it) { 
     unsigned char mychar = *it; 
     ++table[mychar]; 
    } 
} 

對所有字符內循環迭代:其實你可以處理來自std::string S中的數據已經被讀取。它從當前處理的字符(即,從*it)獲得unsigned char,因爲char可能是帶符號的類型並且產生可能不太好的負值。 ASCII字符都是正值,但是,例如,來自我名字的u變音符號ü可能會成爲負值;我猜這對於你的輸入來說不是一個真正的問題,但我更喜歡那些即使意外的事情發生也能正常工作的代碼。

在任何情況下,此循環在std::getline()失敗時終止,因爲沒有其他數據。如果你想讀取數據再次,你要麼需要打開一個新的std::ifstream或重置std::ifstream你有:

myfile.clear();      // clear error flags 
myfile.seekg(0, std::ios_base::beg); // move to the start of the file 

要實際讀取單個字符作爲int你可以使用

mychar = myfile.get(); 

就個人而言,我傾向於使用迭代器來讀取字符,但:

for (std::istreambuf_iterator<char> it(myfile), end; it != end; ++it) { 
    char mychar = *it; // well, you could keep using *it, of course 
    // ... 
} 
+1

從問題中的代碼判斷,不妨讀取和打印這些行,但是從行中而不是文件再次獲取字符,並手動添加新行。儘管如此,這絕對是很好的知識。 – chris

+0

@chris:好點!我更新了答案,提到可以立即使用這些行。 –

+0

好主意 - 但是究竟如何從印刷的線條中取出字符? – James

0

使用fgetc()。你可以傳遞一個FILE指針。

+0

謝謝。錯字固定。 –

相關問題