1

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.

user123
  • 8,970
  • 2
  • 31
  • 52
user3255422
  • 13
  • 1
  • 3
  • Sorry, forgot in C++. – user3255422 Jan 30 '14 at 23:56
  • I've added the tag for you (and removed a couple of non-meaningful others). In the future, please add the language as a tag so your question is clear, and so that the search feature can find it for future readers searching for help in that tag. Thanks. – Ken White Jan 30 '14 at 23:58

4 Answers4

7

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.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
4
void split(int input, int& first, int& second) {
   first = input / 10;
   second = input % 10;
}
Basilevs
  • 22,440
  • 15
  • 57
  • 102
0

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

int firstNumber = cNum[0]-'0';
int secondNumber = cNum[1]-'0';
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
0

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

Roxxorfreak
  • 380
  • 2
  • 10