C字符串在C和C ++大写 [英] C string to uppercase in C and C++
本文介绍了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 ++函数
#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));
因此,我们具有不确定的行为。什么编译器在这种情况下,做的是评估求++
在 TOUPPER(* BEG)
在C其中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屋!
查看全文