473,837 Members | 1,598 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 2940
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
6560
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
13864
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
1970
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
13404
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
14989
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
2647
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
2924
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
12599
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
4510
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
9830
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
9682
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10562
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...
0
10263
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9390
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...
1
7803
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6989
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5842
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4036
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.