String formatting program

Hello, I am having trouble with a program that is supposed to determine Whether the user entered an item number in the required format: three digits, a hyphen, and two digits. Use a sentinel value to end the program. I tried incorporating similar code from earlier in the chapter, but I’m unsure why my program isn’t working. It runs but doesn’t have output. Any help would be much appreciated.

/* Joe McMahon C++ 4
*/
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>

using namespace std;

int main()
{
string item = "";

while (item != "-1")
{
cout << "Item number (-1 to stop)(XXX-XX): " << endl;
getline(cin, item);

if (item.length() == 6)
{
if (item.at(0) >= '0' && item.at(0) <= '9'&& item.at(1) >= '0' && item.at(1) <= '9' && item.at(2) >= '0' && item.at(2) <= '0'
&& item.at(2) >= '9' && item.at(4) >= '0' && item.at(4) <= '9' && item.at(5) >= '0' && item.at(5) <= '9')
{
if (item.at(3) == '-')
{
cout << "Valid format" << endl;
}
else
cout << "invalid format" << endl;
}//end if
}//end if
}//end while

system("pause");
return 0;
}//end of main
Last edited on
Take a look at this:

item.at(2) >= '0' && item.at(2) <= '0' && item.at(2) >= '9'

I guess you want this:

item.at(2) >= '0' && item.at(2) <= '9'
Okay, thanks for catching that.
Topic archived. No new replies allowed.