Sunday, July 12, 2009

C++: Converting unsigned int to int?

I want to perform a little calculation using a length of a string in C++. Im new to this. :(





Example:





string myString = "Hello";


int myCalc;





myCalc = 100-(myString.Length); // is this correct? I want to minus string's length from 100.





But it gives compile error: "error C2440: 'type cast' : cannot convert from 'unsigned int (__thiscall std::basic_string%26lt;char,struct std::char_traits%26lt;char%26gt;,class std::allocator%26lt;char%26gt; %26gt;::*' to 'int'


Conversion is a valid standard conversion, which can be performed implicitly or by use of static_cast, C-style cast or function-style cast"








I tried casting with "int(myString.Length)" but it doesnt work. :(





Please help me out.

C++: Converting unsigned int to int?
length in standard C++ is a function. You need to call it using myString.length()





There shouldn't be a problem putting an unsigned int into an int variable. The compiler is probably complaining that you're trying to convert a function (length) into an int, since you left out the parentheses.
Reply:thanx others too! Report It

Reply:I haven't learned C++ yet( opertune word there is yet) but in Visual Basic when you want to utilize a Str varialble and a Int variable you must declare them seperately and then use the


Val() option to translate. this will allow you to set arguments for converting string varialbes to integer or vise versa.





example intcalc = Val(strCalc)





dont know if that works or if it is even support in C++ but it never hurts to take a look.
Reply:try making myCalc unsigned...


unsigned int myCalc...might work!





Additional details(added later on)


man o man


1) there is nothing that is Length it is length (C++ is case sensitive)


2) it is function so correct call would be myString.length()





then it runs on gcc compiler





best of luck!
Reply:C++ I managed to avoid thus far, but I think AM post's is correct. Make myCalc an unsigned int.





I don't know how many bytes an int type in C++ is, but for the sake of illustration, lets say it is 1 byte.





An unsigned int can take on the values 0..255


Int can be -128..0..127.





Obviously you cannot stuff an insigned int into an int. The type cast can't help you because you run into the same problem. It can't map the silly things.





-Dio
Reply:You want to cast using "(unsigned int)", like this:





myCalc = 100-(unsigned int) (myString.Length);





Now, if you change the declaration of myCalc to





unsigned int myCalc;





you could avoid the whole issue. However, if the string length is greater than 100, you'll get a very large number as a result, which could be bad.


No comments:

Post a Comment