2014-12-31 39 views
-3

這就是我到目前爲止;我想在文本文件中有一個所有字符和空格的概率的數組,但是我對數據類型有問題。C++中的頻率表

int main() 
{ 
float x[27]; 
unsigned sum = 0; 
struct Count { 
    unsigned n; 
    void print(unsigned index, unsigned total) { 

     char c = (char)index; 
     if (isprint(c)) cout << "'" << c << "'"; 
     else cout << "'\\" << index << "'"; 
     cout << " occured " << n << "/" << total << " times"; 
     cout << ", propability is " << (double)n/total << "\n"; 
    } 
    Count() : n() {} 
} count[256]; 
ifstream myfile("C:\\text.txt"); // one \ masks the other 
while (!myfile.eof()) { 
    char c; 
    myfile.get(c); 
    if (!myfile) break; 
    sum++; 
    count[(unsigned char)c].n++; 
} 
for (unsigned i = 0; i<256; i++) 
{ 
    count[i].print(i, sum); 
} 
x[0] = count[33]; 
int j=68; 
for(int i=1;i<27;i++) 
{ 
    x[i]=count[j]; 
    j++; 
} 
return 0; 
} 
+0

您是否正在計算文件c:\ text.txt中的字母?或者是「c:\ text.txt」只是一個令人困惑的示例字符串? – Unimportant

+0

yes @ user1320881我也對此感到困惑。您目前正在嘗試計算文件字符串本身的字符「C:\ text.txt」。 –

+0

是的這是文件的位置 –

回答

2
#include <iostream> 
#include <fstream> 
#include <cctype>  
using namespace std; 

double probabilities[256]; // now it can be accessed by Count 

int main() 
{ 
    unsigned sum = 0; 
    struct Count { 
    unsigned n; 
    double prob; 
    void print (unsigned index, unsigned total) { 
     // if (! n) return; 
     probabilities[index] = prob = (double)n/total; 
     char c = (char) index; 
     if (isprint(c)) cout << "'" << c << "'"; 
     else cout << "'\\" << index << "'"; 
     cout<<" seen "<<n<<"/"<<total<<" times, probability is "<<prob<<endl; 
    } 
    Count(): n(), prob() {} 
    operator double() const { return prob; } 
    operator float() const { return (float)prob; } 
    } count[256]; 
    ifstream myfile("C:\\text.txt"); // one \ masks the other 
    while(!myfile.eof()) { 
    char c; 
    myfile.get(c); 
    if (!myfile) break; 
    sum++; 
    count[(unsigned char)c].n++; 
    } 
    for (unsigned i=0; i<256; i++) count[i].print(i,sum); 
    return 0; 
} 
結束

我整合了各種修改建議 - 謝謝!

現在,誰找到4種方法來獲取實際概率?

+0

這個'fopen'只適用於linux,它只能調用linux內核系統調用 –

+0

@Saher不,'fopen'是C和C++標準。應該在任何有文件系統的系統上工作。 –

+0

錯誤錯誤C4996:'fopen':此函數或變量可能不安全。考慮使用fopen_s代替。要禁用棄用,請使用_CRT_SECURE_NO_WARNINGS。詳細信息請參見在線幫助。 –

0

您正在分配一個大小爲1000000的緩衝區100萬個字符。

char file[1000000] = "C:\text.txt"; 

這並不好,因爲緩衝區中的額外值不能保證爲零,可以是任何值。

對於Windows來閱讀文件,你需要這樣的東西。我不會給你解決方案,你需要學習使用msdn和文檔來完全理解這一點::

你需要首先包含來自SDK的#include <windows.h>標題。

在這裏看看這個例子:http://msdn.microsoft.com/en-us/library/windows/desktop/aa363778(v=vs.85).aspx

這個例子作爲附加文件到另一個。你的解決方案是類似的,而不是寫入其他文件的列表,處理緩衝區來增加你的本地變量和更新表的狀態。

不要爲緩衝區設置大量的緩衝區,因爲緩衝區空間不足會導致溢出。你應該這樣做就像例如:

  • 讀一些字節的緩衝區
  • 過程,緩衝和增加表
  • 重複,直到你到達文件

    while (ReadFile(hFile, buff, sizeof(buff), &dwBytesRead, NULL) && dwBytesRead > 0) { // write you logic here }

+0

iam試圖將文本文件保存在數組中字符,但我不是沒有數組的大小,所以我認爲該紐約將是好 –

+0

這不是你做的方式,那麼,你應該讀取文件到一個緩衝區,並做計數 –

+0

iam對不起idont知道如何,如果你可以告訴我,這將是偉大的 –