Hello guys! First time posting! I am trying to have a user input ID information for a student, and for the ID it could be for example:
00000001
00123000
12345678
I know the to_string function is supposed to convert a number to an integer, but this seems to fail and I think it is due to the zeros in the input. I also tried this code below, but it still seems to fail.
1 2 3 4 5 6 7 8 9 10 11 12 13
int count = 0;
while (ID != 0) {
if (ID % 10 == 0)
{
count++;
ID= ID/ 10;
}
else
{
ID= ID/ 10;
count++;
}
}
My count is to just count how many digits are added for the ID (It has to be an 8 digit length)
Any suggestion on how to convert a number to a string which includes trailing and leading zeros
Say someone inputs 00001234 or 00234000 --> I have to check if this is a valid 8 digit input.
I tried to convert to_string, but it does not work for trailing or leading zeros so I can not check if the user inputted a correct ID of length 8.
I basically take the number 00001234 and check to see if that number that was inputted is indeed 8 digits or not
How do you actually read the input. to_string doesn't bother about leading zeros.
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter a number: ";
int num;
std::cin >> num;
std::cout << "The number you entered: " << std::to_string(num) << '\n';
}
Output:
Enter a number: 00001234
The number you entered: 1234
I think it is time to post the whole program so everyone can see what you have done.
Without see what you have done no one knows what you started with.
As thmm demonstrated a numeric type variable does not store leading (0) zeros. A string will.
I think you may be misunderstanding the "std::to_string()" function. This converts a numeric variable to a string, but since the numeric variable does not store leading (0) zeros they do not show up in the string.
I have an idea, but it would help everyone to know how you are getting your input to start with.
You need to think of the ID as a string, not a number. It's just a little special because the string is made up of digits. So read the ID as a string and then validate it the way JLBorges shows.