gpt4 book ai didi

C++ tolower/toupper 字符指针

转载 作者:太空宇宙 更新时间:2023-11-04 14:37:58 24 4
gpt4 key购买 nike

你们知道为什么下面的代码会在运行时崩溃吗?

char* word;
word = new char[20];
word = "HeLlo";
for (auto it = word; it != NULL; it++){
*it = (char) tolower(*it);

我正在尝试将 char*(字符串)小写。我正在使用 visual studio。

谢谢

最佳答案

您不能将 itNULL 进行比较。相反,您应该将 *it'\0' 进行比较。或者更好的是,使用 std::string 并且永远不用担心 :-)

总而言之,当遍历 C 风格的字符串时。您应该一直循环,直到您看到的字符'\0'。迭代器本身永远不会是 NULL,因为它只是指向字符串中的一个位置。迭代器具有可以与 NULL 进行比较的类型这一事实是您不应直接接触的实现细节。

此外,您正在尝试写入字符串文字。这是一个禁忌:-)。

编辑:正如@Cheers 和 hth 所指出的。 - 如果给定负值,Alf, tolower 可能会中断。很遗憾,我们需要添加一个强制转换,以确保如果您向它提供 Latin-1 编码数据或类似数据,它不会中断。

这应该有效:

char word[] = "HeLlo";
for (auto it = word; *it != '\0'; ++it) {
*it = tolower(static_cast<unsigned char>(*it));
}

关于C++ tolower/toupper 字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33880649/

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