C++方法返回字母B,当输入为A时,直到ZZ
C++方法返回字母B,当输入为A时,一直到Z,如果输入为Z,则该方法应返回AA;如果输入为AA,则该方法应返回AB,一直到ZZ。请查找我正在尝试的示例程序C++方法返回字母B,当输入为A时,直到ZZ,c++,stdstring,C++,Stdstring,C++方法返回字母B,当输入为A时,一直到Z,如果输入为Z,则该方法应返回AA;如果输入为AA,则该方法应返回AB,一直到ZZ。请查找我正在尝试的示例程序 void getString(string s){ for (char ch = 'A'; ch<= 'Z';) { cin >> ch; ch++; cout<< ch; if (ch = 'Z') {
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;
}
使用if ch='Z'代替if ch='Z'
=运算符用于为变量赋值。但是==是一个比较运算符:
if (ch = 'Z') // assign `Z` to ch and check if it's not `\0` (always true)
if (ch == 'Z') // Compare ch with `Z`
char res=k+j;不能连接字符,应仅对元素使用strcat或+运算符
试试下面的例子:
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;
}
请调试的方法有很多种,几乎所有这些方法都应该指出程序中一个非常致命的缺陷:在条件中使用赋值而不是比较来实现相等。您还陷入了使程序不可移植的陷阱。在C++规范中没有要求“A”@ KEKAV:所以最好使用“Z”==CH,这样如果你错过了它,它会给你一个错误。@血液危险或只是启用编译器警告来得到警告:使用赋值的结果作为条件而不带括号。非常感谢。我无意中放置了一个标志。有人能帮我写代码吗?非常感谢您的帮助。@keshavsingh您的问题解决了吗?此时向我抛出错误char res=strcatk,j;错误为44 27 C:\Users\bharg\Documents\test1.cpp[error]从“char”到“char*”的转换无效[-fpermissive]