+ 3

Is there a way that I can only use 1 digit of a variable instead of all of them?

For example: int example = 13; int Numbers; Numbers = example; //is there a way that I can only have example's "3" set equal to Numbers? Instead of setting 13 equal to numbers.

29th Aug 2019, 10:54 AM
Mythical Coding
Mythical Coding - avatar
3 Respuestas
+ 3
Numbers = example % 10 This way numbers will be equal to 3 But if you wanna choose any digit from a number than you can convert it to a string and then choose by index
29th Aug 2019, 11:09 AM
Eliya Ben Baruch
Eliya Ben Baruch - avatar
0
int a = 34; string b = to_string(a); cout << b[0] << b[1]; // or cout << b.at(0) << b.at(1)
29th Aug 2019, 6:40 PM
rodwynnejones
rodwynnejones - avatar
0
If you know the number u really want to make use of. Let's say u want to make use of the last digit, u can do something like this int example = 13; int Numbers = example%10; Note the module operator which returns the remainder which in our case will be the last digit (3) But let's say you want to use a digit in between some numbers, all u have to do is convert to string, using indexing, get your value and convert to int Let's take 1673 as the number, and u need the digit 7* Your code should look like this int userNumber = 1673 string desiredDigit = to_string(userNumber); // converting the int to string..... Remember to #include <string> so as to make use of the string methods. desiredDigit = desiredDigit.at(2); converting back to int int luckyNumber= stoi(desiredDigit); cout << "Value of Lucky Number ==" <<luckyNumber I hope this helps Happy Coding
31st Aug 2019, 1:23 AM
Isaac Frank
Isaac Frank - avatar