Find a digit in a number

Jul 8, 2020 at 1:48pm
Write your question here.

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++

Thanks
Jul 8, 2020 at 2:04pm
One option is to convert to number into a string and search the string.
Jul 8, 2020 at 2:25pm
I looked that up but it's very confusion.
can you help me with that?
I'm not supposed to use While though as quite early in the studies
Jul 8, 2020 at 2:37pm
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.
Jul 8, 2020 at 2:47pm
What are you allowed to use ?
Jul 8, 2020 at 3:33pm
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";

or if you insist on reading them as numbers:
http://www.cplusplus.com/reference/string/to_string/
Last edited on Jul 8, 2020 at 3:38pm
Jul 8, 2020 at 4:29pm
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.

Thank you



Jul 8, 2020 at 9:12pm
you can also convert a string to a number :)
Topic archived. No new replies allowed.