質問

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.

役に立ちましたか?

解決

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.

他のヒント

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

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

int firstNumber = cNum[0]-'0';
int secondNumber = cNum[1]-'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...

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top