473,725 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

any STL/string function available for determing string contains numeric


Is their any single fuction available in C++ that can determine that a
string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff" , It can also contain zero

Apr 4 '07 #1
14 2929
ni**********@st .com wrote:
Is their any single fuction available in C++ that can determine that a
string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff" , It can also contain zero
No. You would have to try one of the C library numeric conversion
functions on the string's contents.

--
Ian Collins.
Apr 4 '07 #2
No even that(strtoul, strtod) would not be possible as strtoul ask for
base(16 for hex, 10 for dec)
and my string can containg a non valid format as "0xffff12yz z" or
"0xaa_AMERI CA" or "AMERICA" or "0xffff"
I just want to check for the rigth possible numeric value.....
Its content does not matter to me
Ian Collins wrote:
ni**********@st .com wrote:
Is their any single fuction available in C++ that can determine that a
string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff" , It can also contain zero
No. You would have to try one of the C library numeric conversion
functions on the string's contents.

--
Ian Collins.
Apr 4 '07 #3
ni**********@st .com wrote:
No even that(strtoul, strtod) would not be possible as strtoul ask for
base(16 for hex, 10 for dec)
and my string can containg a non valid format as "0xffff12yz z" or
"0xaa_AMERI CA" or "AMERICA" or "0xffff"
I just want to check for the rigth possible numeric value.....
Its content does not matter to me
Ian Collins wrote:
>ni**********@st .com wrote:
>>Is their any single fuction available in C++ that can determine that a
string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff" , It can also contain zero
How about outputting the string to a stringstream and then
trying to read a double? If it reads sucessfully and the
stream does not have any characters left in it, it is a
number. I'm not sure if this will work for hex numbers
though, but you might try reading an integer as a side-check.

HTH,
- J.
Apr 4 '07 #4
ni**********@st .com wrote:

Please don't top-post.
Ian Collins wrote:
>>ni**********@ st.com wrote:
>>>Is their any single fuction available in C++ that can determine that a
string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff" , It can also contain zero

No. You would have to try one of the C library numeric conversion
functions on the string's contents.
No even that(strtoul, strtod) would not be possible as strtoul ask for
base(16 for hex, 10 for dec)
and my string can containg a non valid format as "0xffff12yz z" or
"0xaa_AMERI CA" or "AMERICA" or "0xffff"
I just want to check for the rigth possible numeric value.....
Its content does not matter to me
Then you'll have to parse the string scanning for valid number patterns.

--
Ian Collins.
Apr 4 '07 #5
On Apr 4, 12:22 am, nishit.gu...@st .com wrote:
Is their any single fuction available in C++ that can determine that a
string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff" , It can also contain zero

you could try regexp's
http://freshmeat.net/projects/cpp_regex/

bool isValidNumber( string str ) {

if( str[1] == 'x' ) {
verify proper hex chars
some func to convert to hex
return true
}
else {
ostringstream oss( str )
double num;
num << oss;

if( num is valid )
return true
else
return false
}

} // end of isValidNumber

you could even return an int or enumeration to determine what type
with further tests
Apr 4 '07 #6
On Apr 4, 6:22 am, nishit.gu...@st .com wrote:
Is their any single fuction available in C++ that can determine that a
string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff" , It can also contain zero
Boost::regex.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 4 '07 #7
verdverm wrote:
On Apr 4, 12:22 am, nishit.gu...@st .com wrote:
>Is their any single fuction available in C++ that can determine that a
string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff" , It can also contain zero


you could try regexp's
http://freshmeat.net/projects/cpp_regex/

bool isValidNumber( string str ) {
if(str.length() <2) // do something or the next line crashes
if( str[1] == 'x' ) {
verify proper hex chars
some func to convert to hex
return true
}
else {
ostringstream oss( str )
double num;
num << oss;

if( num is valid )
return true
else
return false
Not really. For the string "123ZZZ" num is valid,
while "123ZZZ" is not a valid number.

Conversely, for the string "123" num may go eof
after reading and hence become invalid, while "123"
is a valid number.
}

} // end of isValidNumber

you could even return an int or enumeration to determine what type
with further tests
- J.
Apr 4 '07 #8
On Apr 4, 5:40 pm, Jacek Dziedzic
<jacek.dziedzic .n.o.s.p....@gm ail.comwrote:
verdverm wrote:
On Apr 4, 12:22 am, nishit.gu...@st .com wrote:
Is their any single fuction available in C++ that can determine that a
string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff" , It can also contain zero
you could try regexp's
http://freshmeat.net/projects/cpp_regex/
bool isValidNumber( string str ) {

if(str.length() <2) // do something or the next line crashes
if( str[1] == 'x' ) {
verify proper hex chars
some func to convert to hex
return true
}
else {
ostringstream oss( str )
double num;
num << oss;
if( num is valid )
return true
else
return false
Not really. For the string "123ZZZ" num is valid,
while "123ZZZ" is not a valid number.
The usual formulation in such cases is:

return oss >num >std::ws && oss.get() == EOF ;

If you don't want to allow whitespace, do
oss.unsetf( std::ios::skipw s ) ;
before, and drop the "<< std::ws".

The problem here is that there is no one target type which will
accept all possible numbers. If you're willing to use two
streams, however, something like the following should work:

std::ostringstr eam si( str ) ;
si.unsetf( std::ios::basef ield ) ;
std::ostringstr eam sd( str ) ;
int i ;
double d ;
return (si >i >std::ws && si.get() == EOF)
|| (sd >d >std::ws && sd.get() == EOF) ;

Personally, I'd go with something like:

static boost::regex const
number( "^[:space:]*[+-]?"
"(" "([1-9][0-9]*)"
"|" "(0[0-7]*)"
"|" "(0[xX][0-9a-fA-F]+)"
"|" "([0-9]+\.[0-9]*([Ee][+-]?[0-9]+)?)"
"|" "(\.[0-9]+([Ee][+-]?[0-9]+)?)"
"|" "([0-9]+[Ee][+-]?[0-9]+)"
")[:space:]*$" ) ;
return regex_match( str, number ) ;
Conversely, for the string "123" num may go eof
after reading and hence become invalid, while "123"
is a valid number.
The eofbit will be set after reading "123", but this doesn't
mean that the stream has failed. It only means that any further
attempt to read the stream will fail. (Note that std::ws is a
manipulator, which never "fails", i.e. it never sets failbit.)
}
} // end of isValidNumber
you could even return an int or enumeration to determine what type
with further tests
With boost::regex, you can capture the substrings which matched
parts of the regular expression in parentheses. Within the
or's, only one should not be empty, and which one tells you
which or matched.

My own regular expression class allows matching several regular
expressions in parallel, with the return code indicating which
one matched:
static Gabi::RegularEx pression const
number =
Gabi::RegularEx pression( "[+-]?[1-9][0-9]*", 10 ) ;
| Gabi::RegularEx pression( "[+-]?0[0-7]*", 8 ) ;
| Gabi::RegularEx pression( "[+-]?0[Xx][0-9a-fA-F]+", 16 )
| Gabi::RegularEx pression( "[+-]?[0-9]+\.[0-9]*([Ee][+-]?
[0-9]+)?", 0 )
| Gabi::RegularEx pression( "[+-]?\.[0-9]+([Ee][+-]?
[0-9]+)?", 0 )
| Gabi::RegularEx pression( "[+-]?[0-9]+[Ee][+-]?[0-9]+",
0 ) ;

std::pair< int, std::string::co nst_iterator >
result
= number.match( str.begin(), str.end() ) ;
return result.second == str.end()
? result.first
: -1 ;

This would return -1 if no match, 0 for a floating point value,
and the base for an integer value. (I've since added features
to force an error if the match doesn't go to the end of the
string, so you could just use "return number.match(.. .).first;",
but this version isn't yet present at my site.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 5 '07 #9
Thanx James...1 more query..is regex a part of standard C++???
James Kanze wrote:
On Apr 4, 5:40 pm, Jacek Dziedzic
<jacek.dziedzic .n.o.s.p....@gm ail.comwrote:
verdverm wrote:
On Apr 4, 12:22 am, nishit.gu...@st .com wrote:
>Is their any single fuction available in C++ that can determine thata
>string
>contains a numeric value.
>The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
>"0xffff" , It can also contain zero
you could try regexp's
>http://freshmeat.net/projects/cpp_regex/
bool isValidNumber( string str ) {
if(str.length() <2) // do something or the next line crashes
if( str[1] == 'x' ) {
verify proper hex chars
some func to convert to hex
return true
}
else {
ostringstream oss( str )
double num;
num << oss;
if( num is valid )
return true
else
return false
Not really. For the string "123ZZZ" num is valid,
while "123ZZZ" is not a valid number.

The usual formulation in such cases is:

return oss >num >std::ws && oss.get() == EOF ;

If you don't want to allow whitespace, do
oss.unsetf( std::ios::skipw s ) ;
before, and drop the "<< std::ws".

The problem here is that there is no one target type which will
accept all possible numbers. If you're willing to use two
streams, however, something like the following should work:

std::ostringstr eam si( str ) ;
si.unsetf( std::ios::basef ield ) ;
std::ostringstr eam sd( str ) ;
int i ;
double d ;
return (si >i >std::ws && si.get() == EOF)
|| (sd >d >std::ws && sd.get() == EOF) ;

Personally, I'd go with something like:

static boost::regex const
number( "^[:space:]*[+-]?"
"(" "([1-9][0-9]*)"
"|" "(0[0-7]*)"
"|" "(0[xX][0-9a-fA-F]+)"
"|" "([0-9]+\.[0-9]*([Ee][+-]?[0-9]+)?)"
"|" "(\.[0-9]+([Ee][+-]?[0-9]+)?)"
"|" "([0-9]+[Ee][+-]?[0-9]+)"
")[:space:]*$" ) ;
return regex_match( str, number ) ;
Conversely, for the string "123" num may go eof
after reading and hence become invalid, while "123"
is a valid number.

The eofbit will be set after reading "123", but this doesn't
mean that the stream has failed. It only means that any further
attempt to read the stream will fail. (Note that std::ws is a
manipulator, which never "fails", i.e. it never sets failbit.)
}
} // end of isValidNumber
you could even return an int or enumeration to determine what type
with further tests

With boost::regex, you can capture the substrings which matched
parts of the regular expression in parentheses. Within the
or's, only one should not be empty, and which one tells you
which or matched.

My own regular expression class allows matching several regular
expressions in parallel, with the return code indicating which
one matched:
static Gabi::RegularEx pression const
number =
Gabi::RegularEx pression( "[+-]?[1-9][0-9]*", 10 ) ;
| Gabi::RegularEx pression( "[+-]?0[0-7]*", 8 ) ;
| Gabi::RegularEx pression( "[+-]?0[Xx][0-9a-fA-F]+", 16 )
| Gabi::RegularEx pression( "[+-]?[0-9]+\.[0-9]*([Ee][+-]?
[0-9]+)?", 0 )
| Gabi::RegularEx pression( "[+-]?\.[0-9]+([Ee][+-]?
[0-9]+)?", 0 )
| Gabi::RegularEx pression( "[+-]?[0-9]+[Ee][+-]?[0-9]+",
0 ) ;

std::pair< int, std::string::co nst_iterator >
result
= number.match( str.begin(), str.end() ) ;
return result.second == str.end()
? result.first
: -1 ;

This would return -1 if no match, 0 for a floating point value,
and the base for an integer value. (I've since added features
to force an error if the match doesn't go to the end of the
string, so you could just use "return number.match(.. .).first;",
but this version isn't yet present at my site.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Apr 5 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6557
by: Bernard Drolet | last post by:
Hi, I have a column containing a string; the string always starts with a letter (a-z), followed by an undefined number of letters, then one number or more. The REGEXP would look like *+ I need to extract the letters at the beginning in an SQL query or in PL/SQL
5
13857
by: ief | last post by:
hi all, i'm trying to check the length of a numeric value in a string. this is what i need to do: I have a string "Mystring (253)" and a string "SecondString (31548745754)" Now i have to check if the string contains more than 3 numeric characters because i must only process the ones with more than 3.
5
1962
by: jupiter | last post by:
Hi guys, I have a problem. I have a list which contains strings and numeric. What I want is to compare them in loop, ignore string and create another list of numeric values. I tried int() and decimal() but without success. eq of problem is
232
13297
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *$ If the...
13
14980
by: nishit.gupta | last post by:
Is their any fuction available in C++ that can determine that a string contains a numeric value. The value cabn be in hex, int, float. i.e. "1256" , "123.566" , "0xffff" Thnx
1
2644
by: Ryan Liu | last post by:
Hi, I read a csv file to a datatable. I don't know what are the column types at this moment, so I treat all columns as string type. After I read data from file, I use dataTable.Select(condition) to select some lines. The problem is with numeric columns, since in datatable, it is string type, it compares rows as string so make Select() return wrong set of rows.
6
2919
by: frohlinger | last post by:
Hi, I need to perform some numeric calculations on a numeric float value, that is received as wstring. I would like to perform a check before converting the wstring to float, checking that indeed the wstring contains a numeric value. This is the actual conversion: double fValue = _wtof(strValue.c_str()); if strValue contains some characters (e.g.: 'aaa'), _wtof returns 0, therefore I do not really know that the input was initially...
3
12591
by: amija0311 | last post by:
Hi, I am new using DB2 9.1 database by windows base. I want to query the data that contain string then translate the string into integer using DB2. The problems is If the data is null, i got the problem to translate. How to translate string also allow null data to integer. If null data it will read as space. My Data :- GEOSEG_ID SEQNO
6
4506
by: Richard | last post by:
I'm validating a date and time string which must be EXACTLY of the format yy-mm-dd hh:mm:ss and extracting the six numeric values using sscanf. I'm using the format string "%2u-%2u-%2u %2u:%2u:%2u" which works, but it allows each numeric field to be either 1 or 2 digits in length. Also the man page for sscanf says that preceeding white space before a numeric is ignored.
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.