How can I find whether a digit is in a number?
I want to get a number from the user and find out whether that number contains a specific digit, for example: get 789 and find out if 8 is in the number.
It's easy in Python, but I can't find the right function in C++
You can peel off the digits of a number by repeatedly dividing by 10:
1 2 3 4
while (num) {
int digit = num % 10; // "%" returns the remainder of the division
num = num / 10; // integer division truncates any fractions
}
So you could compare "digit" to the digit you're looking for and return true if you find it.
There's a special case here though: zero. If the number passed in is zero then the while loop will never execute. So you have to check for zero explicitly.
where did num come from? If the user typed it, just read it as text, and its trivial.
roughly:
string num;
cin >> num; //for now as a beginner assume user types numbers without checks.
//auto means let the compiler figure out the type. I think result is some kind of integer but
//not sure which type, so, I will use auto
auto result = num.find("8"); //where did this 8 come from, did user type in digit too?
if(result == string::npos) cout << "nope"; //npos means not found, or 'no such position'
else cout <<"yep";
Thank you for all the responses.
It's my first time so I didn't realise how many details I missed.
I'm studying an online course. the basics still. Didn't study loops yet so can't use them.
I need to get a number from the user and check if it contains a certain digit that is pregiven in the code.
I can't read the number as a string because I also have to use it for calculation in another place.
after reading your advises and understanding how "to_string" works I managed.