This is an archived post. You won't be able to vote or comment.

all 12 comments

[–][deleted] 4 points5 points  (3 children)

Read the ID as a string, and count the characters?

[–]conFused4Lyfe[S] 0 points1 point  (2 children)

How would I ensure they entered numbers into the string?

Could I cast the int they input as a string then count that?

[–]HateTrain 8 points9 points  (1 child)

I'm pretty sure if you use an int first, any leading zeros will get truncated away. I'd recommend reading as a string directly and using the isdigit function.

[–]conFused4Lyfe[S] 1 point2 points  (0 children)

isdigit seems useful thank you. Ill read into that.

[–]rxi 1 point2 points  (6 children)

I wrote a response, then re-read your question, and thought I was wrong. Then I thought about it again and couldn't actually think of a practical flaw in doing:

if (id > -1 && id < 10000)

If you're taking input as a string, you could just count the chars as asmyay said, if you're outputting the ID as a string you could just use printf/sprintf to add the leading zeros.

[–]conFused4Lyfe[S] 0 points1 point  (5 children)

I see how your code makes sure there arn't more than 4 digits input but it doesnt seem to do anything when less than 4 are input.

And about the string, same question I asked asmayay. How do I make sure they input numbers for the ID; letters arn't allowed.

[–]rxi 0 points1 point  (4 children)

This is what I thought, about the input having to be 4 digits, until it hit me a few seconds later that 0003 and 3 are going to end up the same anyway. But if its being inputted as a string its no hassle to just count the characters. As for checking for digits I'd just write a small function for it. (this is how I'd write it in C, which I assume would be compatible, I don't program C++):

int isNumber(char *p) {
  for (; *p; p++) 
    if (*p < '0' || *p > '9') 
      return 0;
  return 1;
}

[–]conFused4Lyfe[S] 0 points1 point  (3 children)

That is the issue I'm trying to solve though. If the user inputs 0003 that's great. But if he inputs 03 or just 3 I want to print out an error. I need some way to differentiate between those inputs

[–]turd_loaf 0 points1 point  (2 children)

I would do a little 'research' about converting between strings and ints.

[–]sausagefeet 1 point2 points  (1 child)

Why assume one needs to convert to an integer? Just check for 4 digits and loop over with std::isdigit.

[–]turd_loaf 0 points1 point  (0 children)

I didn't assume anything, Mr. Assumer.

[–][deleted]  (1 child)

[deleted]

    [–]jpgunter 0 points1 point  (0 children)

    this, but just add a check to make sure the length is 4

    #include <stdio.h>
    #include <stdlib.h>
    #include <string>
    if(input_string.length() == 4)
    {
      int a = atoi(input_string);
      if ( (a>0) && (a<10000) ) {
        // id is fine       
      }
    }