Entry length of computer input (cin)?

Here I have an incomplete program. The instructor tells us (in her comments) that the number entered should be a 4-digit number (which I assume also includes anything with 0XXX in it and so on). How do I make the program give an error message if the user does not enter 4 digits within this current if statement?

if (KEYBOARD)
{ cout << "Enter item number: ";
cin >> num;
}
else
num = rand() % 9000 + 1000;
return num;

There is also a comment where she states the price of an item should be as low as 0.10 to as high as 10.09, how do I set an if statement withing the current if to do something similar to the first one with 0.10 and 10.09 as the parameters? I already know it involves >= and <=, but I don't know how to implement it.


if (KEYBOARD)
{ cout << "Enter price for item " << num << " : ";
cin >> price;
}
else
price = double (rand() % 1000 + 10 ) / 100;
return price;

or is this all arbitrary to completing the program and I should move on instead?

EDIT: There is also a point where I need to use the PRNG (Pseudo-Random Number Generator) in C++, how exactly do I set a range for this number (Like between 1 and 15 for example)?
Last edited on
if you want to assume 0123 to be for digit number, you first have to read input into a string, then check it's length, and then convert it to int.[edit]silly of me. Bazzy is right[/edit] I doubt you should allow 0123 though, unless your teacher told you to. juct check if input >= 1000 && input < 10000. same for 0.1 and 10.09

you're using rand correctly already. rand will return a number from 0 to some-big-number. you have to use % and + to adjust the range.
Last edited on
you need to read the input first and then validate the number you just read.
Not like you have above, with a condition test and then read input ( you can't check that the input is valid before the user types something )

All 4 digit number have less than 5 digits, so they are all in the range [0,10000[

You already have some calls of rand which produce a number in some range:
num = rand() % 9000 + 1000; will produce numbers between 1000 and 1000+9000-1
Thank you very much Bazzy.

I've decided though that maybe the addition of a condition test for the entry may be arbitrary to completing the program. I have class later today, so I'll ask my instructor then. For now I'll focus on finishing the rest of the program.
Topic archived. No new replies allowed.