Check first number for zero

I'm trying to error check whether a user puts in zero as their first number in an integer... I can check for any number but zero, but I'm not sure how to make my loop work for zero.. I'm probably just not thinking it through correctly. Please help.

My loop for any number but zero check (assuming there are no negative numbers or decimals):

1
2
  		while (firstDigit >= 10)
			firstDigit /= 10;
Last edited on
closed account (Dy7SLyTq)
read it in as a string and test it that way
I think you'll have to take the input as std::string and then after validation, use stringstream.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <sstream>

int main() {
  std::cout << "Please enter the number: " ;
  std::string input_str;
  std::cin >> input_str;
  while ( input_str[0] == '0' ) {
    std::cout << "First digit should not be zero. Please re-enter: " ;
    std::cin >> input_str;
  }
  std::stringstream str;
  str << input_str;
  unsigned int my_number;
  str >> my_number;
  return 0;
}
Topic archived. No new replies allowed.