C字符串到C和C ++中的大写 [英] C string to uppercase in C and C++

查看:177
本文介绍了C字符串到C和C ++中的大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While I was putting together a to-uppercase function in C++ I noticed that I did not receive the expected output in C.

C ++函数

C++ function

#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;
}

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

The output is the expected result with the first character missing

OOBAR

任何人都知道为什么结果在C?中编译时被截断。

Does anyone know why the result gets truncated while compiling in C?

推荐答案

问题是

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

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

So we have undefined behavior. What the compiler is doing in this case is evaluating beg++ before toupper(*beg) In C where in C++ it is doing it the other way.

这篇关于C字符串到C和C ++中的大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆