Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to select random two digits from anywhere in a number with C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

// Function to select random two non-consecutive digits from a number
std::string getRandomTwoDigits(long long number) {
    std::string numStr = std::to_string(number);

    if (numStr.size() < 2) {
        return "Error: number must have at least 2 digits";
    }

    // Generate two distinct random indices
    int i = std::rand() % numStr.size();
    int j;
    do {
        j = std::rand() % numStr.size();
    } while (j == i);  // ensure different positions

    // Form the two-digit string
    std::string result;
    result.push_back(numStr[i]);
    result.push_back(numStr[j]);

    return result;
}

int main() {
    std::srand(std::time(0));  

    long long num = 1234567;
    std::string randomTwo = getRandomTwoDigits(num);

    std::cout << "Random two digits: " << randomTwo << std::endl;
}

 
/*
run:
 
Random two digits: 41

*/

 



answered Nov 25, 2025 by avibootz
...