2

I am working on a project where the user is prompted to enter a zip code. I need to verify it is a five digit number (I don't need to verify it is an actual zip code).

Here is a portion of my code.

string userInput;
cout << "Zip Code> ";
getline(cin, userInput, '\n');


while (stoi(userInput)<10000 || stoi(userInput) > 99999){
    cout << endl << endl << "You must enter a valid zip code. Please try again." << endl;
    cout << "Zip Code>" << endl;
    getline(cin, userInput, '\n');
}

PropertyRec.setZipCode(stoi(userInput));

This works fine unless the zip code starts with a zero. If it does, the validation is no good and the initial zero never saves to the variable once the input string is converted to an integer.

Should I leave the zip code as a string when saving to the database? If so, how can I verify there are exactly 5 characters and each character is numeric?

Zong
  • 6,160
  • 5
  • 32
  • 46
Brent
  • 171
  • 1
  • 2
  • 10

3 Answers3

9

Use std::all_of, isdigit and string::size() to determine if the zip code is valid:

#include <string>
#include <algorithm>
#include <cctype>
//...
bool isValidZipCode(const std::string& s)
{
   return s.size() == 5 && std::all_of(s.begin(), s.end(), ::isdigit);
}

Live Example

Declarative Programming plug:

Note that if you say out loud the line in the isValidZipCode function, it fits your description (the string must have a size equal to 5 and "all of" the characters must be a digit).

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
4

Since you are receiving input as a std::string, you can use std::string::length (or std::string::size) to ensure you have the right amount of characters:

if (userInput.length() != 5)
{
    // Input is invalid
}

To ensure they're only numbers, as @user4581301 points out you can use std::all_of and isdigit (or check out answers in this question)

if (userInput.length() == 5 && std::all_of(s.begin(), s.end(), ::isdigit))
{
    // Input is valid
}

It's also worth noting that the following line

PropertyRec.setZipCode(stoi(userInput));

Will remove any leading 0 you have, so you may need to store your zip code as a std::string (unless you implement handling that will assume any zip code that's < 5 has leading 0's, but it's likely far easier to store it exactly as-is)

Community
  • 1
  • 1
Tas
  • 7,023
  • 3
  • 36
  • 51
0

You can use string size function for getting the size of the string. Save the string size in other variable and validate it whether it less than five or not.