gpt4 book ai didi

c++ - 使用 isalpha() C++ 的问题

转载 作者:行者123 更新时间:2023-12-02 18:58:55 24 4
gpt4 key购买 nike

这里对 C++ 来说是个新手。我正在编写一个非常简单的程序,用于检查包含两个字符的字符串中的字符是否按字母顺序排列。如果一个字符是字母顺序的,我想用字符“_”替换它,但是,我的 if 语句似乎有问题,我一生都无法弄清楚。我觉得修复很简单,但想不出答案。任何帮助将不胜感激。

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
string passCode;

cin >> passCode;

if (isalpha(passCode.at(0)) == true){
passCode.at(0) = '_';
}
if (isalpha(passCode.at(1)) == true){
passCode.at(1) = '_';
}


cout << passCode << endl;
return 0;
}

最佳答案

问题是 std::isalpha不返回 bool,它返回 int - 并且仅保证成功时返回非零值。

当你比较时:

if (isalpha(passCode.at(0)) == true)

您正在隐式地将 true 转换为整数值(在本例中为 1)——这不是 std::isalpha 的结果code> 正在返回。

您可以通过删除 == true 并允许将 int 值隐式转换为 bool 来轻松解决此问题:

if (isalpha(passCode.at(0))){
passCode.at(0) = '_';
}
if (isalpha(passCode.at(1))){
passCode.at(1) = '_';
}

Live Example

关于c++ - 使用 isalpha() C++ 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65855238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com