【问题标题】:toupper() and tolower() return ASCII number when should be character [duplicate]toupper() 和 tolower() 在应该是字符时返回 ASCII 数字 [重复]
【发布时间】:2021-10-27 18:40:21
【问题描述】:

在这个问题中,我使用 C++。我有一个使用字符串变量 'word' 的 for 循环,并且应该以大写形式返回这个单词。

for(int i=0;i<word.size();i++){
            cout<<toupper(word[i]);
        }

但是,它返回的不是单词本身,而是它的 ASCII 码。 而且,当我这样写时,一切正常

string a;
for(int i=0;i<word.size();i++){
            a=toupper(word[i]);
            cout<<a;
        }

我只是好奇为什么会这样,为什么 toupper() 不能返回字符串变量。

【问题讨论】:

  • 好的,非常感谢!

标签: c++ c++17


【解决方案1】:

问题是std::toupper 返回一个int,而不是char

你需要投射它:

std::cout << static_cast<char>(std::toupper(word[i]);

std::toupper(以及std::tolower 和所有字符分类函数)使用int 而不是char 的原因是它们继承自C,其中int 用于所有字符。

【讨论】:

  • 旁注:toupper 也接受 int,而不是 char,如果您将 signed char 传递给它,这可能会导致一些奇怪且几乎难以理解的错误。请参阅之前链接的文档中的the notes
  • @user4581301:问题不在于toupper 采用int,而是指定它采用unsigned char 值。可能导致问题的是负,而不是类型
  • 关于你提到 C 对所有字符使用 ìnt` 的部分,这是不准确的。
  • 在将参数传递给&lt;cctype&gt; 标头中声明的函数时,请参阅this answer 以了解有关为什么需要强制转换为unsigned char 的背景的更多信息。
  • @AlaaMahran 的措辞可能会更好,但 ctypes.h 中的所有字符测试和转换实用程序函数都采用 int 而不是 char
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多