Hallo
I have this assignment to print only alphabets in a C++ string. It works for most input but when [ and ] are present in the input they are printed as well.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG]";
for(int i=0;i<input.size();i++)
{
if(input[i] >='A' && input[i] <= 'z')
//if(isalpha(input[i]))
cout<<input[i];
}
cout<<endl;
return 0;
}
The problem is here:
You are using uppercase
'A'and lowercase'z'.The range
A-zis not same asA-Z+a-z.The ASCII value of
Zis90and that ofais97.Between them there are 6 other characters which you are considering as alphabets.
To allow only uppercase and lowercase alphabets you should use:
or even better just use
isalpa: