-1

I can't get the right output.. please help me.. and it should return false when I put number as the first character for the name like this ,

Enter the name of the first rectangle: rec 1a

Invalid input. Type 'rec' following by the name or 'stop' if done.

Try again! Enter the name of the first rectangle: rec a

Enter a's bottom left x and y coords: 9 3

Enter a's length and height: 2 8

i am only allow to use these 3, not anything else..

#include <iostream>
#include <string>
#include <vector>

and my code is

bool promptread_rec(const string & prompt, const string & invalid, const string & usedname, string & input, vector<Rectangle> & list)
{ 
    cout << prompt;
    getline(cin, input);

    if (input == "stop")
    {
       return true;
    }
    else if (input.substr(0,4) != "rec ")
    { 
       cout << invalid << endl;
       return false;
    }
    else if (input[4] == '0' || input [4] == '1' || ......)
    {
       cout << invalid << endl;
       return false;
    }
    else if (list.size() > 0)
    {
       for (int i = 0; i < list.size(); i++)
       {
           if (input == list[i].getName())
           {
               cout << usedname;
               return false;
           }
       }
       return true;
    }
    else 
    {
       return true;
     }
}

is there a faster way to do it?? need to avoid all numbers e.g. 0,1,2,3,...,9

  • 3
    Unfortunately, I don't think anyone's going to go through all that. Try compressing your code to fit the specific problem. Also, unrelated but, you should ditch the getters and setters for point imo. It's really annoying to call GetX() and GetY() just because you're following OOP rules too strictly for no benefit. – Ben Apr 16 '14 at 16:36
  • 1
    Indeed there is too much unneeded information. Instead of posting your entire code, post only the relevant parts (in this case, for example, just the section that reads the string) – Bruno Ferreira Apr 16 '14 at 16:43
  • 1
    sorry about posting the whole thing.. I just revised it – user3542052 Apr 16 '14 at 19:00

2 Answers2

2

From the header cctype, you may use the function isalpha(c) on the first character of the string, like:

string a = "a1234";
assert(isalpha(a.at(0)) == true);
a = "1234";
assert(isalpha(a.at(0)) == true);

Just remember to access a.at(0) only if the string is not empty or else it will throw a std::out_of_range exception

References:

Bruno Ferreira
  • 1,621
  • 12
  • 19
0

Since you cannot use any other headers you have to implement your own functions, which is actually simple enough for ASCII characters:

bool IsLetter(char c) {
  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

bool IsDigit(char c) {
  return c >= '0' && c <= '9';
}

Using these two helper functions you can write a function to test if a name is valid:

bool IsValidName(const std::string &name);

I leave this for you to implement.

bolov
  • 72,283
  • 15
  • 145
  • 224