how do i convert a char to an int?
how do i convert a char to an int?
Have you tried itoa()?
**edit** you need to include stdlib.h to use itoa()Code:char cNum[10]; int iNum=4; itoa(iNum,cNum,10); //now cNum="4";
Last edited by jdinger; 09-02-2002 at 07:12 PM.
how would you convert a string to a float value?
when i compile my program i get this error:
error C2664: 'atof' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const char *'
it won't let me convert the string to a float.
>Use atof().
No, use strtod. The ato* functions are unsafe because they result in undefined behavior if the value is outside of the range for the particular type. You also can't determine how many characters of the original string were a part of the conversion. Both of these problems can be solved by using the strto* functions instead.
-Prelude
My best code is written with the delete key.
it also says this after the above error message:
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
sorry from the original post I didn't realize you were using strings (since you said char). I thought you were using a c style char array.
Last edited by jdinger; 09-02-2002 at 07:57 PM.
>error C2664: 'atof' : cannot convert parameter 1 from 'class std::basic_string<snip>' to 'const char *'
This is because you are using a C++ string, not an array of char terminated by a nul character. For your code to work, you should convert the string to a C string:
Once again, I recommend using strtod instead of atof for safety reasons.Code:atof ( my_string.c_str() );
-Prelude
My best code is written with the delete key.
does the strtod function automatically stop reading when it reads a letter? how do i use the strtod function?
From MSDN:
Convert strings to a double-precision value.
double strtod( const char *nptr, char **endptr );
double wcstod( const wchar_t *nptr, wchar_t **endptr );
Each of these functions converts the input string nptr to a double
Parameters
nptr
Null-terminated string to convert
endptr
Pointer to character that stops scan
Remarks
The strtod function converts nptr to a double-precision value. strtod stops reading the string nptr at the first character it cannot recognize as part of a number. This may be the terminating null character. wcstod is a wide-character version of strtod; its nptr argument is a wide-character string. Otherwise these functions behave identically
***the lowly Grayson_Peddie bows to the Code Goddess.
thanks for the rebuke, Prelude. I didn't have any experience with strtod before (atof hadn't failed me (yet)), so I learned something new.**
Last edited by jdinger; 09-02-2002 at 08:06 PM.
okay, so in order to not get the error message above when using the strtod function, i would need to write it like this:
x = strtod( string.c_str() , &stopstring.c_str() ).;
is this right?