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?
" 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):
'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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With