Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning C4244 \ '=': conversion from 'int' to 'char', possible loss of data?

Tags:

c++

c++11

When writing a program for solving a puzzle, I encountered a warning in the following snippet:

std::string str = "hello";

for (int i = 0; i < str.length(); ++i)
    str[i] = toupper(str[i]); //make every letter capital       
//  ^^ warning

I'm getting a warning on the last line above.

Warning C4244 \ '=': conversion from 'int' to 'char', possible loss of data?

Is there any way to get rid of this warning?

like image 291
blackmamba591 Avatar asked Sep 06 '16 12:09

blackmamba591


People also ask

What is error c4244?

" warning C4244: 'argument': conversion from 'wchar_t' to 'const _Elem', possible loss of data" It arises from a file called xtring: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.27.29110\include\xstring(2390,23):

What does 'conversion' mean in C++?

'conversion' conversion from 'type1' to 'type2', possible loss of data An integer type is converted to a smaller integer type. This is a level-4 warning if type1 is int and type2 is smaller than int. Otherwise, it is a level 3 (assigned a value of type __int64 to a variable of type unsigned int ). A possible loss of data may have occurred.

What is the data type of char in C++?

It so happens that a "char" data type in C# is actually a 16-bit integer, corresponding to wchar_t in C++. Use wide chars (wchar_t) not narrow (char). Convert::ToChar returns a wchar_t, not a char. It so happens that a "char" data type in C# is actually a 16-bit integer, corresponding to wchar_t in C++. >Use wide chars (wchar_t) not narrow (char).


1 Answers

Cast the str[i] to a char explicitly like this:

str[i] = (char)toupper(str[i]);

Or:

str[i] = static_cast<char>(toupper(str[i]));

To make the operation more C++ friendly. std::toupper returns an int, which makes the compiler complain. By casting the return value, you tell the compiler you know what you are doing.

As a side note, I recommend using boost::to_upper() on the string at once, like this:

#include <boost/algorithm/string.hpp>
#include <string>

std::string str = "hello";

boost::to_upper(str); //Is HELLO

std::string newstr = boost::to_upper_copy<std::string>("hello"); //is HELLO
like image 192
Arnav Borborah Avatar answered Sep 25 '22 19:09

Arnav Borborah