![]() |
![]() |
|||||
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
|
Q: Converting AnsiStrings to numbers and converting numbers to AnsiStringsSummary of tasksThis FAQ covers the following tasks:
Task 1: Converting AnsiStrings to integers:The VCL provides four functions to convert AnsiStrings to integers: the global StrToInt and StrToIntDef functions, and the ToInt and ToIntDef member functions of AnsiString. The StrToIntDef and ToIntDef functions allow you to specify a default integer to return if the string doesn't contain an valid integer. In addition to the VCL functions, you can still use streams or the C run time library to convert an AnsiString to an int. Each strategy is outlined below. StrToIntStrToInt is a global VCL function. The code for StrToInt resides in SOURCE\SYSUTILS.PAS. The prototype for StrToInt is located in INCLUDE\SYSUTILS.HPP. This header file is automatically included into your project when VCL.H is included. StrToInt is easy to use: you simply pass it an AnsiString and it returns an integer. // this code converts a string // into an integer number AnsiString str("29"); int nValue; nValue = StrToInt(str);StrToInt generates an exception if the string does not contain a valid integer. The exception is of the type EConvertError. This code demonstrates how you can catch the exception. AnsiString str="Get lost Buffy!"; int nValue; try { nValue = StrToInt(str); } catch (EConvertError &e) { Application->MessageBox("It wasn't a number." , "error", MB_OK); return; }AnsiString::ToInt The Ansistring class contains a ToInt member function that converts the string into an integer. The declaration for ToInt looks like this (DSTRING.H): int __fastcall ToInt() const; Notice that ToInt is declared as a const member function, which allows you to call ToInt on constant strings. The code for ToInt is located in SOURCE\VCL\DSTRING.CPP. If you have the VCL source, open up DSTRING.CPP. You should see that ToInt simply calls the global StrToInt function. In fact, all of the AnsiString conversion methods call their global counterparts. Since ToInt simply calls StrToInt, you can surround ToInt with a try-catch block to catch any conversion exceptions. Here is an example of how to use the ToInt function. AnsiString str("29"); int nValue; nValue = str.ToInt();StrToIntDef and AnsiString::ToIntDef StrToIntDef and AnsiString::ToIntDef allow you to specify a default value that will be returned if the AnsiString doesn't contain a valid integer. If the string is not an integer, these functions return the default value instead of generating an exception. If you have the VCL source, DSTRING.CPP reveals that the ToIntDef method of AnsiString simply calls the global StrToIntDef function. Here are code examples: // StrToIntDef // this code converts a string from an edit box // into an integer number. Default value is 29. int nValue; nValue = StrToIntDef (Edit1->Text, 29); // AnsiString::ToIntDef // this code converts a string from an edit box // into an integer number. Default value is 29. int nValue; nValue = Edit1->Text.ToIntDef(29);Using the C RTL or iostreams to convert an AnsiString to an integer The VCL StrToInt function requires that the entire string be a valid number. If you call StrToInt for an AnsiString that contains "1100 Grand Avenue", you might expect that the return value will be 1100. Not so. Instead, StrToInt sees that the string contains non-numeric characters and generates an exception. For strings like these, you can use either the C RTL sscanf function, or use an iostream. This technique requires that you call the c_str member function to retrieve a char * that you can pass to the RTL. // using sscanf to read numbers from an AnsiString // you need to add the standard sscanf error handling code // don't forget to #include <stdio.h> int i,j; AnsiString strEdit = "29 100"; sscanf(strEdit.c_str(), "%d %d",&i, &j); ProgressBar1->Position = i; ProgressBar2->Position = j; // using streams to read numbers from an AnsiString #include <sstream> using namespace std; ... int i,j; AnsiString strEdit = "29 100"; istrstream istr(strEdit.c_str(), strEdit.Length()); istr >> i >> j; ProgressBar1->Position = i; ProgressBar2->Position = j; Task 2: Converting AnsiStrings to floating point numbers:The VCL provides two functions that convert AnsiStrings to floating point numbers: the global StrToFloat function and the ToDouble member function of AnsiString (ToDouble simply calls StrToFloat). You can also use streams or the C RTL (see previous code about converting strings to ints). The following example demonstrates how to use StrToFloat and AnsiString::ToDouble. // using StrToFloat to convert an AnsiString to a float AnsiString str("3.14159"); float fValue; fValue = StrToFloat(str); // using AnsiString::ToDouble to convert an AnsiString to a float AnsiString str("3.14159"); float fValue; fValue = str.ToDouble(); StrToFloat returns an 80 bit long double, whereas ToDouble returns a 64 bit double. Both of the preceeding code examples could have used the double data type instead of float. StrToFloat generates an exception if the AnsiString contains invalid text. StrToFloat works by calling the TextToFloat pascal function in SYSUTILS.PAS. The section on how to convert an AnsiString to an integer contained a section that described how to use sscanf or istringstream to extract integer values from a string. These examples could also be extended to floating point types. Task 3: Converting integers to AnsiStrings:The VCL provides two functions to convert an integer to an AnsiString: the global IntToStr function and a version of the AnsiString constructor. Once again, nothing prevents you from using iostreams or the C run time library to do the conversion. The examples below demonstrate each method. IntToStrThe prototype for IntToStr is located in SYSUTILS.HPP, which is automatically included by VCL.H. The code for IntToStr is located in SYSUTILS.PAS. The function would look like this if it were written in C++: AnsiString __fastcall IntToStr(int Value) { AnsiString RetValue; FmtStr(RetValue, "%d", Value); return RetValue; }FmtStr is a pascal function that works a lot like the C sprintf function. The code example below shows how to use IntToStr. int nValue = TrackBar1->Position; AnsiString str = IntToStr(nValue); Edit1->Text = str;AnsiString::AnsiString(int Value) AnsiString contains a constructor that can initialize the string with an integer value. Here's how you do it: int nValue = TrackBar1->Position; AnsiString str(nValue); Edit1->Text = str;Using the sprintf member function of AnsiString In C++Builder 4, Borland added 2 member functions to AnsiString called sprintf and printf. These functions work much like the standalone sprintf function in the RTL. The difference is that AnsiString::sprintf formats the AnsiString object, instead of formatting a char *. The code example below shows how you can use the sprintf member function of AnsiString.// using sprintf to read numbers into an AnsiString int i = 29; int j = 5006; AnsiString str; str.sprintf("The numbers are %d and %d.", i,j); Label1->Caption = str; This is a very useful function. Notice that you don't have to pass a destination buffer to AnsiString::sprintf. This is because the AnsiString itself is the destination. AnsiString contains several other member functions that behave like the sprintf function. They are printf, vprintf, cat_sprintf, cat_printf, and cat_vprintf (the last four may only be available in BCB5 and beyond, check dstring.h to be sure). The printf member funtion works just like sprintf, except that it returns the length of the string after the formatting has been done. sprintf does not return anything. Don't confuse AnsiString::printf with the regular printf function. The RTL printf routine prints to stdout. AnsiString::printf writes to the AnsiString object. The vprintf member of AnsiString behaves sort of like the RTL vprintf function. Unlike sprintf and printf, this function takes a va_list argument, instead of a variable number of arguments. The printf and sprintf routines both rely on the vprintf function for their underlying implementation. All of the cat routines concatenate the formatted string onto whatever was already in the AnsiString. Here is an example that demonstrates cat_sprintf // using cat_sprintf to read numbers into an AnsiString int i = 29; int j = 5006; AnsiString str ("I was already here: "); str.sprintf("The numbers are %d and %d.", i,j); Label1->Caption = str; After calling cat_sprintf, the string contains the text "I was already here: The numbers are 29 and 5006." Using ostringstream to read numbers into an AnsiString You can also use an ostringstream to format an AnsiString variable. In fact, this method may be better than using the sprintf because it does not rely on format codes and variable argument functions. Here is a code example. // using streams to read numbers from an AnsiString #include <sstream> using namespace std; ... int i = 29; int j = 5006; AnsiString str; ostringstream ostr; ostr << "The numbers are "<< i << " and " << j << "." ; str = ostr.str().c_str(); Label1->Caption = str; Task 4: Converting floats to AnsiStrings:The VCL provides several functions that convert floating point numbers to AnsiStrings. You can use the FloatToStr or FloatToStrF global functions, or you can use an alternative AnsiString constructor that takes a double value as an argument. Once again, you can always resort to iostreams or the C RTL (see the examples in how to convert an int to a string). FloatToStr and FloatToStrFBoth FloatToStr and FloatToStrF work by calling a pascal function called FloatToText. FloatToText takes arguments that allow you to customize the format of the resulting string. It allows you to specify the format, the precision, and a number that represents how many digits to display. The format is chosen by specifying a value from the TFloatFormat enum. FloatToStr hard codes the format to ffGeneral, the precision to 15, and the digit value to 0. FloatToStrF allows you to specify these values, which makes it the more useful function of the two. Here is a code example of both. // an example of FloatToStr float fValue = 100.2; AnsiString str = FloatToStr(fValue); // an example of FloatToStrF float fValue = 100.2; AnsiString str = FloatToStrF(fValue,ffGeneral,7,5); // an example of FloatToStrF using scientific notation float fValue = 10e-6; AnsiString str = FloatToStrF(fValue,ffExponent, 7,5); The third argument to FloatToStrF determines the precision of the conversion. This value should be 7 or less for single precision float types, and should be 15 or less for double's. The last parameter is the digits argument. This meaning of the digits argument varies for different conversion modes (ffExponent verses ffGeneral). Consult the help file for specific details. AnsiString::AnsiString(double Value)The AnsiString class provides a constructor that allows you to initialize the string with a double precision floating point value. The constructor works by calling FloatToStrF. // an example of AnsiString::AnsiString(double src) float fValue = 100.2; AnsiString str(vFalue); Label1->Caption = str; | ||||||
All rights reserved. |