2012-11-30 167 views
1

我正在做一個字符數通過char c = cin.get()。我的輸出的實施例將是: 一個:53 B:32個 C:29 等。什麼原因導致字符數不準確,真的很大?

對於字母表中的一個,我發現了一個大瘋狂9位數字。然後當我使用另一個具有更多字符的輸入文件時,這些數字是6位數字,太大而不準確。這種表型的任何想法?

再次,對不起,這是學期末的緊縮時間。我很感激那裏的任何幫助。

int main (int argc, char *argv[]) 
{ 

int count [26] = { }; 
char alpha [26] = { }; 

char c; 

c = cin.get();  
while(!cin.eof()) 
{ 
    if (isalpha(c)) 
    { 
    c = tolower(c);  
    }  

    count [ c - 'a']++; 
    alpha [ c - 'a'] = c; 

    c = cin.get(); 
    }  

    for (int i = 0; i<26; i++) 
    { 
    cout << alpha[i] << ":" << count[i] << endl; 
    } 

    } //end main  

這裏的輸出:(編輯)

a:224 
b:50 
c:70 
d:20 
e:167772180 
f:10 
g:40 
h:66 
i:28 

這裏的輸入:(編輯)

aaaaaaaaAAAAAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAAAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaBBBB

製造這些改變,BU t將其仍然「懸」:

c = cin.get();  
while(c=cin.get()) 
{ 
    c = tolower(c); 
    if (isalpha(c)) 
     continue;  


    count [ c - 'a']++; 
    alpha [ c - 'a'] = c; 

    }  

    for (int i = 0; i<26; i++) 
    { 
    cout << alpha[i] << ":" << count[i] << endl; 
    } 

    } //end main  
+1

您不應該假定ASCII正在使用中,或者使用'while(!eof())'。改用'while(cin.get(c))'。 – chris

+1

和顯而易見的問題,你輸入所有26對是嗎? –

+0

@KarthikT所有26個字母,一些大寫。但是,每個字母要麼一致地大寫,要麼小寫。 – harman2012

回答

4

如果輸入文件包含比點兒別的字母,任何事情都有可能發生,因爲你正在訪問的陣列wtih出界指數。也許你的意思是:

while(!cin.eof()) 
{ 
    if (isalpha(c)) 
    { 
     c = tolower(c);  

     count [ c - 'a']++; 
     alpha [ c - 'a'] = c; 
    } 

    c = cin.get(); 
}  

例如當您的數據包含換行符(10)時,您正在訪問索引爲10 - 97 = -87的alpha。這可能寫入count[4]的最重要字節10。

+0

你是不是指'(isalpha(c))'? – harman2012

+0

@ harman2012 - 剛剛意識到'continue'也會在循環結束時跳過'cin.get()'。編輯我的答案。 – Henrik

+0

是的,新的線條是有道理的!儘管查看該文件,但會在「s」處返回一個新行。我會仔細檢查這個新發現。因此,較小的文件起作用,並且將計數放在isalpha()下是有意義的。非常感謝! – harman2012

相關問題