我的函数显示垃圾,有时它显示干净的结果

时间:2012-03-15 06:58:23

标签: c++ function char uppercase

我必须计算给定行中的大写和小写字母的数量。对于这个赋值,我必须使用以\ 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

2 个答案:

答案 0 :(得分:3)

仔细看看这一行:

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

如何知道要输出多少个字符?你真的应该使用std::stringstd::vector<char>

如果您想要最简单的修复,请在打印前执行此操作:Uppercase_array[k]=0;。 C风格的字符串的末尾标有一个终止的nul(零字节),它告诉处理它们有多大的函数。

答案 1 :(得分:1)

如果您引用的“垃圾”是√"中的GDARE√",那么答案是将空终止符\0添加到Uppercase_array的最后一个字符处}。也就是说,在do / while循环之后,添加Uppercase_array[k] = '\0'