### Select certain number

Hello,

Lets say A is equal to 12345678912345. How can I select the third and fourth number in the numbers as input in B. And the eighth and ninth number as input in C. And B and C will be combined to become D. Can someone help me? Thank u.
Last edited on
Easiest is to convert A to a string, extract the wanted digits, convert them to an int and add them together.
 ``1234567891011121314151617181920212223242526`` ``````#include #include #include using std::string; using std::cout; using std::cin; using std::to_string; /* Lets say A is equal to 12345678912345. How can I select the third and fourth number in the numbers as input in B. And the eighth and ninth number as input in C. And B and C will be combined to become D. */ int main() { long long A = 12345678912345; string s = to_string(A); int B = (s[2] - '0') * 10 + (s[3] - '0'); // * has higher priority than - int C = (s[7] - '0') * 10 + (s[8] - '0'); int D = B * 100 + C; cout << "B = " << B << "\nC = " << C << "\nD = " << D << "\n\n"; }``````

Output:
 ```B = 34 C = 89 D = 3489 ```

 ``12345678910111213141516171819202122232425262728293031323334353637`` ``````#include #include #include using namespace std; using INT = unsigned long long; vector digitise( INT n ) { vector digits; for ( ; n; n /= 10 ) digits.push_back( n % 10 ); reverse( digits.begin(), digits.end() ); return digits; } int main() { INT A, B, C, D; // cout << "Input A: "; cin >> A; A = 12345678912345; vector digits = digitise( A ); if ( digits.size() < 9 ) { cout << "Number not large enough"; return 1; } else { B = 10 * digits[2] + digits[3]; C = 10 * digits[7] + digits[8]; D = 100 * B + C; // Is this what you meant by "combined"? // D = B + C; // Or just add them up? } cout << "B, C, D = " << B << ", " << C << ", " << D << '\n'; }``````

You could also do it with substrings:
 ``123456789101112131415161718192021222324252627`` ``````#include #include using namespace std; using INT = unsigned long long; int main() { INT A, B, C, D; // cout << "Input A: "; cin >> A; A = 12345678912345; string sA = to_string( A ); if ( sA.size() < 9 ) { cout << "Number not large enough"; return 1; } else { B = stoi( sA.substr( 2, 2 ) ); C = stoi( sA.substr( 7, 2 ) ); D = 100 * B + C; } cout << "B, C, D = " << B << ", " << C << ", " << D << '\n'; }``````

or with a sledgehammer:
 ``12345678910111213141516171819`` ``````#include #include using namespace std; using INT = unsigned long long; int main() { INT A, B, C, D, power = 1; // cout << "Input A: "; cin >> A; A = 12345678912345; while ( power <= A ) power *= 10; assert( power >= 1000000000 ); B = ( A / ( power / 10000 ) ) % 100; C = ( A / ( power / 1000000000 ) ) % 100; D = 100 * B + C; cout << "B, C, D = " << B << ", " << C << ", " << D << '\n'; }``````

 `B, C, D = 34, 89, 3489`
Last edited on
Thanks @Thomas1965 and @lastchance for your help. It works well. :)
Topic archived. No new replies allowed.