gpt4 book ai didi

c++ - 在 C 和 C++ 中将 C 字符串转换为大写

转载 作者:IT老高 更新时间:2023-10-28 21:54:04 27 4
gpt4 key购买 nike

当我在 C++ 中组合一个大写函数时,我注意到在 C 中我没有收到预期的输出。

C++ 函数

#include <iostream>
#include <cctype>
#include <cstdio>

void strupp(char* beg)
{
while (*beg++ = std::toupper(*beg));
}

int main(int charc, char* argv[])
{
char a[] = "foobar";
strupp(a);
printf("%s\n", a);
return 0;
}

按预期输出:

FOOBAR


C 函数

#include <ctype.h>
#include <stdio.h>
#include <string.h>

void strupp(char* beg)
{
while (*beg++ = toupper(*beg));
}

int main(int charc, char* argv[])
{
char a[] = "foobar";
strupp(a);
printf("%s\n", a);
return 0;
}

输出是缺少第一个字符的预期结果

OOBAR

有谁知道为什么在 C 中编译时结果会被截断?

最佳答案

问题是里面没有序列点

while (*beg++ = toupper(*beg));

所以我们有未定义的行为。在这种情况下,编译器所做的是在 toupper(*beg) 之前评估 beg++ 在 C 中,而在 C++ 中它以另一种方式进行。

关于c++ - 在 C 和 C++ 中将 C 字符串转换为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086007/

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