Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

checking if a string is a positive decimal number

Status
Not open for further replies.

chineerat

Technical User
Oct 12, 2003
42
0
0
TT
Hi there!
i am have a problem with the following code.
i would like to check if the string is a positive decimal number.
if the string has a letter or minus sign it steps into the 'if' loop, which is perfect.
However if the string has a decimal point, it steps into the loop, which is not suppose to happen

the conditions for stepping into the 'if' loop are if a letter, minus sign are present.

if (!isdigit(principal)) excludes any non digit character i assume...
how do i exclude a decimal point in a string?

is there anyway to fix this using the isdigit or isalpha funtions?
thanks



#include<iostream>
#include<string>
using namespace std;
int main(){
string principal ;
int period = 0;
float interest = 0;
cout<<"Program to Calculate Sum of Money"<<endl;
cout<<"Enter Principal to 2 decimal places "<<endl;
cin>>principal;

for(int i= 0; i < principal.size(); i++){// checking for letter and minus sign
if( !isdigit(principal)){
cout<<"Principal is NOT a Positive number "<<endl;
cin>>principal;
i= -1;
}}
return 0 ;
}
 
What's a problem? This program detects all but digit chars in its input. There is another problem in this code: add eof/errors test - for example:
Code:
if (cin >> principal)
{
  // Input check:
}
else
{
  // Say good bye...
  break;
}
Also don't forget >>std::string features: if a user type "1 2", the principal string value is "1" and the next read gets "2".
 
Try this for you if statement:

Code:
  if (!IsDigit(principal[i] && principal[i] != "."){
    // Your code
  }


HyperEngineer
If it ain't broke, it probably needs improvement.
 
THanks guys

HyperEngineer
your code worked perfectly
THANKS ALOT
 
why not use atof


float value = atof(principal);
//if user entered text then the value = 0
//if the user entered neg number then the value < 0
if(value <= 0)
{
cout<<"Principal is NOT a Positive Number"<<endl;
cin>>principal;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top