how to find spaces in between characters in string?

May 14, 2014 at 10:49pm
I'm writing a program that returns true if and only if the input are numbers and contain one decimal, e.i. (8.3). Also it cannot contain space in between the numbers, e.i. (8 8) would return false. Leading and trailing space are okay, e.i ( 8888 ). I'm stuck on finding white space in between the input, how do I got about doing it? I'm thinking about using Arrays, but not sure how to set it up.

Last edited on May 14, 2014 at 10:50pm
May 15, 2014 at 1:28am
try a regular expression
May 15, 2014 at 1:42am
No. RE is overkill. (And not acceptable for HW assignments.)

Just count the number of digits in the string. It should be equal to the length of the string minus one. Then check to see if the string contains a decimal point ('.'). If it does, then the string is validated. In any other case, the string fails.

Hope this helps.
May 15, 2014 at 3:33am
Thanks for your help guys, the following is the function I have. It works as I need to. The only thing I'm missing/having problems is how to go about finding if I have any spaces in between my numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

bool okNumber( const string &number )
{

    cout<<"okNumber function"<<endl;
    int sumPeriod =0;
    for (int i=0; i<number.size();i++){
            if (number[i] == '.'){
                sumPeriod++;
            } if(sumPeriod > 1){
                    cout<<"False period > 1"<<endl;
                    return false;
                }
                if (number[i]>= '0' && number[i]<='9'){
                    cout<<"Okay"<<endl;
                    return true;
                }
                if (number[i]>'0'){
                    cout<<"False. No letters/characters allowed"<<endl;
                    return false;
                            }
}

}
May 15, 2014 at 7:40am
Just saying. Your brackets are a nightmare to look at.
Having said that..... why not use isspace()?

1
2
3
for (int i = 0; i < strlen (number); i++)
     if (isspace(number[i]))
           //do something. 
Last edited on May 15, 2014 at 7:41am
Topic archived. No new replies allowed.