【问题标题】:Using toupper on char returns the ascii number of the char, not the character?在 char 上使用 toupper 返回字符的 ascii 编号,而不是字符?
【发布时间】:2017-11-30 14:57:22
【问题描述】:
int main()
{

char hmm[1000];

cin.getline(hmm, 1000);
cout << hmm << endl;    //this was to test if I could assign my input to the array properly
for (int sayac = 0; hmm[sayac] != '@'; sayac++) {
    if (!isdigit(hmm[sayac])) {
        if (islower(hmm[sayac])) 
            cout << toupper(hmm[sayac]);
        else if (isupper(hmm[sayac]))
            cout << tolower(hmm[sayac]);
        else
            cout << hmm[sayac];
    }
}

"编写一个程序,将键盘输入读取到@符号并回显输入 除了数字,将每个大写字符转换为小写,反之亦然。 (不要忘记 cctype 系列。)“

我正在从入门书中做这个练习。但是当我运行它时,它返回字符的 ascii 顺序,而不是字符的大写/小写版本。无法弄清楚问题所在。谁能告诉我为什么?

(我可能对练习有其他问题,如果有请不要纠正。我想自己解决(除了我解释的问题),但我无法检查其他问题,因为我有这个问题。

【问题讨论】:

  • 不,它没有。
  • 是的,它does(某种意义上)
  • 在 C++ 中没有字符类型,只有整数类型通常用于表示字符。一些 i/o 工具,尤其是狭窄的 iostream,会将char 值解释为表示字符。全局 toupper 是从旧 C 继承的函数,它接受 int 参数并返回 int。要通过cout 显示该字符,请将其转换为char。请注意toupper 的参数必须是非负数,否则EOF,这意味着作为参数的char 值应首先转换为unsigned char。否则,可能是UB。另外,请先致电setlocale
  • 旁注:+1 表示尝试过,获得了所有信息,然后明确地仅就该问题而不是其他任何问题寻求帮助。先生,我敢肯定,你会很快学到很多关于这门语言的知识。

标签: c++


【解决方案1】:

写作时

std::cout << toupper('a');

会发生以下情况:

  1. 调用int toupper(int ch),返回一个整数,其值为'A'0x41)。
  2. std::basic_ostream::operator&lt;&lt;(std::cout, 0x41) 被调用,即 int (2) 重载,因为提供了 int

总的来说,它打印“65”。

作为一种解决方案,您可以将大写字母转换为 char

std::cout << static_cast<char>(toupper('a'));

【讨论】:

    【解决方案2】:

    这是一个代表问题。字符和该字符的数值之间没有区别。这完全取决于您选择显示它的方式。例如,字符 'a' 只是一个常量,其值等于字符的数值。

    您遇到的问题是 std::toupperstd::tolower 返回 int 而不是 char。原因之一是它们处理EOF 值,这些值不一定由char 表示。因此,std::cout 看到您正在尝试打印int 而不是char。流式传输int 的标准行为是打印数字。然后解决方案是将结果转换为char 以强制将该值解释为字符。你可以使用std::cout &lt;&lt; static_cast&lt;char&gt;(std::toupper(hmm[sayac]));之类的东西。

    尝试以下方法:

    #include <cctype>
    #include <iostream>
    
    int main()
    {
        char hmm[1000];
    
        std::cin.getline(hmm, 1000);
        std::cout << hmm << std::endl;    //this was to test if I could assign my input to the array properly
        for (int sayac = 0; hmm[sayac] != '@'; sayac++) {
            if (!std::isdigit(hmm[sayac])) {
                if (std::islower(hmm[sayac]))
                    std::cout << static_cast<char>(std::toupper(hmm[sayac]));
                else if (isupper(hmm[sayac]))
                    std::cout << static_cast<char>(std::tolower(hmm[sayac]));
                else
                    std::cout << hmm[sayac];
            }
        }
    }
    

    您还应该考虑使用std::string,而不是任意长度的char 数组。另外,请注意,如果输入字符串不包含 @,则您的行为未定义。

    【讨论】:

    • 感谢您的帮助。为什么我想使用 char 数组是因为这本书还没有教过字符串(尽管我知道足够在这里使用它)所以我想用本书提供的内容来练习
    猜你喜欢
    • 2014-11-15
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    相关资源
    最近更新 更多