Liz Liz -4 years ago 166
C++ Question

if condition too long and including for loop

Hi I am a C++ beginner and here is a problem I am facing when writing a function.

The bool function

isData
is used to see whether the array members are all numbers. Usually the size will be 11 or 9 or 7 so I don't want to hard code it. But I am not sure whether for loop work in if condition. And I will be so grateful if you can show me an easier way to do this.

bool isData(string temp[], int size)
{
if(
for (int i;i<size;i++)
{
59 > +temp[i].at(0) && +temp[i].at(0) > 47 || +temp[i].at(0) == 45
}
)
{
return true;
}
else
{
return false;
}
}

Answer Source

for loops doesn't result in true or false, so for in an if won't work.

instead, run all elements in a for loop and return false if you find a non-number. Otherwise, return true.

Pseudo code for that would be something like this

bool isData(String temp[], int size) {
    for(int i=0; i < size; i++) {
        if( hasOnlyDigits(temp[i]) ) { return false; }
    }
    return true;
}

hasOnlyDigits is a function that would take in string and check if it's a valid number.

Here is a one liner for positive numbers. bool hasOnlyDigits = (temp[i].find_first_not_of( "0123456789" ) == string::npos);

It's non trivial to implement a function which handles all inputs like +.23, -33--33. Implement a function that can handle inputs within your input constraints.

I'll update this answer if I find a robust way to check.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download