문제

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