Reputation: 183
I am reading C++ right now ,and got stuck in the following program.
When I provide string with lower case letter, it provides a fine output, but when I go for upper case letters, it gets stuck after the input.
Here is the code:
`#include <iostream>`
#include <stdio.h>
#include "string.h"
using namespace std;
class base {
public:
int array(){
int i, n, p, z = 0;
char g[50];
string c[50];
char abc;
cout << "Enter the name :" << endl;
cin >> g;
i = 0;
while (g[i] != 0)
if ((g[i] >= 'a' && g[i] <= 'z') || (g[i] <= 'A' && g[i] >= 'Z')){
z++;
i++;
}
cout << "name is of " << z << " elements" << endl;
{
for (p = 0; p < z; p++)
cout << "a[" << p + 1 << "]=" << g[p] << endl;
}
cout << "enter the element no.:";
cin >> n;
if(n >0 && n <= z){
cout << "a[" << n << "]=" << g[n-1] << endl;
}
for (p = 0; p < z; p++){
char integer_string[50];
int integer = p+1;
sprintf(integer_string, "%d", integer);
char other_string[50] = "g[";
strcat(other_string, integer_string);
strcat(other_string, "]");
c[p]= other_string;
}
cout << "Enter the character :";
cin >> abc;
for (p = 0; p < z; p++){
if(g[p] == abc){
cout <<abc<< "=a[" << p + 1 << "]"<< endl;
break;
}
}
return 0;
}
};
//--------------------------------------------------------------
int main(){
base b;
b.array();
return 0;
}
Could you tell me what is the problem in my program?
Upvotes: 0
Views: 126
Reputation: 75062
Try changing
if ((g[i] >= 'a' && g[i] <= 'z') || (g[i] <= 'A' && g[i] >= 'Z'))
to
if ((g[i] >= 'a' && g[i] <= 'z') || (g[i] >= 'A' && g[i] <= 'Z'))
and deleting the three ` , two in the first line and one in the last line.
UPDATE
Adding #incude <cctype>
to the head of the code and using
if (islower(g[i]) || isupper(g[i]))
is better. To avoid depending to the character code.
if (isalpha(g[i]))
may also work.
Upvotes: 1