Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C string to uppercase in C and C++

Tags:

While I was putting together a to-uppercase function in C++ I noticed that I did not receive the expected output in 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; } 

Output as expected:

FOOBAR 


C function
#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 

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

like image 940
Alex Koukoulas Avatar asked Oct 12 '15 16:10

Alex Koukoulas


People also ask

Which C string function converts a string to uppercase?

toupper() function in C The toupper() function is used to convert lowercase alphabet to uppercase. i.e. If the character passed is a lowercase alphabet then the toupper() function converts a lowercase alphabet to an uppercase alphabet. It is defined in the ctype.

Does toupper work on strings in C?

toupper() works on one element ( int argument, value ranging the same as of unsigned char or EOF) at a time. Prototype: int toupper(int c); You need to use a loop to supply one element at a time from your string.

How does toupper work in C?

The toupper() function converts the lowercase letter c to the corresponding uppercase letter. Both functions return the converted character. If the character c does not have a corresponding lowercase or uppercase character, the functions return c unchanged.

How do you convert a string to uppercase?

JavaScript String toUpperCase() The toUpperCase() method converts a string to uppercase letters. The toUpperCase() method does not change the original string.


Video Answer


2 Answers

The problem is that there is no sequence point in

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

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.

like image 55
NathanOliver Avatar answered Sep 22 '22 18:09

NathanOliver


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

leads to undefined behavior.

Whether *beg++ is sequenced before or after std::toupper(*beg) is unspecified.

The simple fix is to use:

while (*beg = std::toupper(*beg))    ++beg; 
like image 33
R Sahu Avatar answered Sep 21 '22 18:09

R Sahu