2012-03-15 63 views
0

我必須計算給定行中的大寫字母和小寫字母的數量。對於這個任務,我必須使用由\ 0終止的字符數組,這就是我所做的。我使用ascii代碼來識別小寫或大寫字母。但是,輸出有時是乾淨的,有時不乾淨。任何幫助將不勝感激。這是我在Dev-C++中的代碼。密切關注這條線由於我的功能顯示垃圾,有些時候它顯示乾淨的結果

#include <iostream> 
#include<conio.h> 
#include<cstring> 


using namespace std; 

int getline(); 
int isupper(char line[]); 
int islower(char line[]); 


int main() 
{ 
    int Month, last_digit;  //initialize variables and char array 
    char temp[255]; 
    getline(); 

    getch(); 
    return 0; 
} 

int getline() 
{ 
    char line[255]; 
    cout << "Enter a sentence: "; 
    cin.getline (line, 255); 
    isupper(line); 
    islower(line); 
    getch(); 
    return 0; 
} 

int isupper(char line[]) 
{ 
    int y, i=0, k=0; int count_uppercase=0; char Uppercase_array[80]; 

    cout<<endl<<"from isupper function"<<endl; 
    do 
    { 
    y=line[i++]; // Convert to int 
    if(y>64 && y<91)  //if it is a Uppercase letter... 
    { 
     Uppercase_array[k]=line[i-1]; 
     k++;   
     count_uppercase++;  //increment the counter... 
    } 
    } 
    while(y); 
    cout<<"Uppercase letter = " <<Uppercase_array; 
    cout<<" number of uppercase = "<<count_uppercase<<endl; 
    cout<<"----------"<<endl; 

    return 0; 

} 

int islower(char line[]) 
{ 
    int z, i=0, count_lowercase=0; 
    cout<<"from lowercase function"<<endl; 
    do 
    { 
    z=line[i++]; // Convert to int 
    if(z>96 && z<123)  //if it is a Lowercase letter... 
    count_lowercase++;  ////increment the counter... 
    } 
    while(z); 
    cout<<"number of lowercase = "<<count_lowercase<<endl;  

    getch(); 
    return 0; 
} 

*******example1 of output***** 
Enter a sentence: Good morning Dad, how ARE u? 

from isupper function 
Uppercase found in that line = GDARE√" number of uppercase = 5 
---------- 
from lowercase function 
number of lowercase = 16 

************example2 of output********* 
Enter a sentence: Good morning Dad how are u? 

from isupper function 
Uppercase letter = GD number of uppercase = 2 
---------- 
from lowercase function 
number of lowercase = 19 
+1

跳到我身上的第一件事是您的Uppercase_array不是空終止。 – Corbin 2012-03-15 07:01:40

回答

1

如果「垃圾」你指的是在GDARE√"√",那麼答案是空終止\0增加的Uppercase_array的最後一個字符。也就是說,在do/while循環之後,添加Uppercase_array[k] = '\0'

+0

清除!我現在很清楚。現在我會記住它。再次感謝!! – T4000 2012-03-15 07:17:41

3

看:

cout<<"Uppercase letter = " <<Uppercase_array; 

它是如何知道有多少個字符輸出?你真的應該使用std::stringstd::vector<char>

如果您想要最簡單的修復方法,請在打印之前執行以下操作:Uppercase_array[k]=0;。 C風格的字符串的末端標有一個終止nul(零字節),告訴處理它們的函數有多大。

+0

太好了,它現在正常工作!你能解釋一下爲什麼Uppercase_array [k] = 0解決了這個問題嗎?我真的很想理解爲什麼這個ligne本身可以解決這個問題。謝謝 – T4000 2012-03-15 07:13:59

+0

如果你寫'\ 0'而不是0,它可能會更清楚。它是空字符,標記字符串的末尾。 (它正好有ASCII值零,這就是爲什麼你*可以*只寫0)。 – Wyzard 2012-03-15 07:18:17

+0

現在清除!我傾向於忘記終止字符串的'\ 0'。比你多! – T4000 2012-03-15 07:26:40