user3255422
user3255422

Reputation: 13

How do I separate a 2 digit number into individual digits?

The program prompts the user to enter a 2 digit decimal number. How do I separate the number into two separate variables after the user enters it?

Later I need to use the first and the second part of the number so they need to be in different variables.

Upvotes: 1

Views: 9025

Answers (4)

Roxxorfreak
Roxxorfreak

Reputation: 380

Assuming you have a character string you can split it in two strings and use atoi() on both...

char s[2];
s[1] = 0;
s[0] = yourstring[0];
int i1 = atoi(s);
s[0] = yourstring[1];
int i2 = atoi(s);

This is of course quick and dirty and does not include any error checking. It will return 0 for invalid characters though...

Upvotes: 0

herohuyongtao
herohuyongtao

Reputation: 50657

You can first read them into char cNum[3] (last one is '\0'), then

int firstNumber = cNum[0]-'0';
int secondNumber = cNum[1]-'0';

Upvotes: 0

Basilevs
Basilevs

Reputation: 23896

void split(int input, int& first, int& second) {
   first = input / 10;
   second = input % 10;
}

Upvotes: 4

Captain Giraffe
Captain Giraffe

Reputation: 14705

Start by dividing the number by ten, there you have the first number.

int i = 99;
int oneNumber = i / 10;

You really should try to get the next one by yourself.

Upvotes: 7

Related Questions