C++ method to return alphabet B
when an input is A
so on till Z
then if the input is Z
the method should return AA
if the input is AA
the method should return AB
, so on till ZZ
. Please find a sample program which I was trying.
void getString(string s){
for (char ch = 'A'; ch<= 'Z';)
{
cin >> ch;
ch++;
cout<< ch;
if (ch = 'Z')
{
cout << "in loop";
for (char k = 'A'; k<= 'Z';){
for (char j = 'A'; j<= 'Z';j++){
char res = k + j;
cout << res;
}
k++;
}
}
}
}
int main() {
getString("");
return 0;
}
Use if (ch == 'Z')
instead of if (ch = 'Z')
=
operator is for assign a value to a variable. But ==
is a compare operator :
if (ch = 'Z') // assign `Z` to ch and check if it's not `\0` (always true)
if (ch == 'Z') // Compare ch with `Z`
With char res = k + j;
you cannot concatenate characters, You should use of strcat()
or use of +
operator just for an element.
Try bellow :
void getString(string s)
{
if(s.length() == 1)
{
if(s[0] == 'Z')
cout << "AA";
else
cout << static_cast<char>(s[0] + 1);
}
else if(s.length() == 2)
{
if(strcmp(s.c_str(), "ZZ") == 0)
{
cout << "ZZ";
}
else
{
if(s[1] != 'Z')
{
cout << s[0] << static_cast<char>(s[1] + 1);
}
else if(s[1] == 'Z')
{
cout << static_cast<char>(s[0] + 1) << 'A';
}
}
}
}
int main() {
char res[3] = {0};
cin >> res;
getString(res);
return 0;
}