problem finding valid decimal number

Hi, I am new to C++, i have just started mt course. I got some problems to solve but don't know how to do it. I need someone who can solve it and explain it to me how it happened! Thanks.
Problem 1.1 You have to complete the given program to check whether a number is valid or not. Write only the process() function. The rules for checking validity are: [15 marks]
1) Input cannot contain any character other than digits or dot(.)
2) At most ONE dot(.) is allowed in the input
3) If there is a dot(.) in the input, it cannot be the last character of the input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include<iostream> 
#include<string>
 using namespace std; 
class myClass{
private: string num;
public:
void input(){
cout << “Enter number:”; getline(cin,num);
}
void process(){
// Complete this function

}
};
int main()
{ myClass c;
 c.input();
 c.process();
 return 0; 
}
Last edited on
The answer is in the question.

You need to check that each character of the "num" is a digit or dot.
You need to disallow multiple dots (easy way is to use a Boolean flag).
You need to make sure the last character is not a dot.

Try taking it one step at a time.
Last edited on
yah!! The problem is i just dnt kno what to write. What should i write in the process to make it happen.
Step 1: Loop through num & check that each character is of a valid value. Stop if one isn't.

Step 2: Keep track of the number of dots. If it becomes larger than one, stop.

Step 3: Check the last character. If it is a dot, stop.

Else: Yay.
can u plz show me the code if possible. thanks
first just try to count the "." characters and see if there are more than one. That is a small task. I'll start you off with that.

1
2
3
4
5
6
int numDots = 0;
for (char ch : num)
{
   if (ch=='.')
      ++numDots;
}


that loop will go through the entire text string "num" looking for .'s and incrementing a counter. If you dont yet understand for loops, you can read about them here http://www.cplusplus.com/doc/tutorial/control/

plug that in to your code and get process() to reject entries with more than one dot. When its working add another check and get that working also. keep going that way, a feature at a time.

i tried bt it didnt work, shows error!!
i tried bt it didnt work, shows error!!


Could you show us the code that you tried it? Quit asking for the code. This is not a free homework site.
Last edited on
Topic archived. No new replies allowed.