Home > Net >  Finding a number within a string and using it in a loop
Finding a number within a string and using it in a loop

Time:10-03

I need the code to check a string for any number at any point in the string, provide an error message if there is, and then loop back to input. Here is what I have at the moment.

 bool isNumber (string accName)
{
                for (int t=0; t < accName.length();   t)
                {
                        if (isdigit(accName[t])== false){
                        return false;
                        }

                        return true;
                } 

I inserted this boolean function into a for statement, but the only output I'm getting is the break from the else statement.

 for(i=0; i<999; i  ){

        getline(cin, accName);

        if (isNumber(accName) == true){

                cout<<"Account name is invalid, please use letters and spaces only."<<endl;
                }

        else{
        break;
        }

I would love some help on this. I've read extensively and can not seem to figure this out.

CodePudding user response:

Your problem is that following line is in the wrong place

return true;

Move it outside of the for loop and it should be fine.

The right way to do this is by using Regular Expressions. If you do not know what that is, you can start reading here

CodePudding user response:

in your method isNumber you are only checking the first Char of the string. If it is a Number you return false, if not you return true. This returning means you exit the method after looking at the first character.

bool isNumber (string accName)
{
       for (int t=0; t < accName.length();   t)
       {
               if (isdigit(accName[t])!=true){
                   return true;
               }
       } 
}
  • Related