How can I count on a different base number in C ++?

My 15-year-old little brother begins to program, and he wrote a neat little program that displays the entire combination of letters and numbers that are six digits or less. His code was a sequencer loop that updated the elements of a char-level array. It looked bad, but definitely quick! I showed him how to make a simple account, and convert these numbers to base 36.

The biggest problem is that my code was much slower than it, due to what I was doing. Is there a way I can just assume base 36 and print a number from 1 to 36 ^ 6?

Ideally, I want to do something like

[base 36]
for(int i = 0; i < 1000000; i++)
   SaveForLaterFileOutput(i);
+5
source share
4

:

char buffer[1024];
for(int i = 0; i < 1000000; i++)
      cout << itoa ( i, buffer, 36);

itoa ( )

cout << setbase (36);
for(int i = 0; i < 1000000; i++)
      cout << i << endl;
cout << setbase (10); // if you intend to keep using cout

+3

, 6- 6 . increment , "", :

#include <algorithm>
#include <iostream>

#define NUM_CHARS 6

// assuming ASCII
// advances through a chosen sequence 0 .. 9, a .. z
// or returns -1 on overflow
char increment(char &c) {
    if (c == 'z') return -1;
    if (c == '9') { c = 'a'; return c; }
    return ++c;
}

int main() {
    char source[NUM_CHARS+1] = {0};
    std::fill_n(&source[0], NUM_CHARS, '0');
    while (true) {
        std::cout << source << "\n";
        int idx = NUM_CHARS;
        // increment and test for overflow
        while (increment(source[--idx]) == -1) {
            // overflow occurred: carry the 1
            source[idx] = '0';
            if (idx == 0) return 0;
        }
    }
}

" " : 6 , , . , , , , .

+2

36: , 36 ^ 6. , ( ), , . , 36 ^ 0. , 36.

, - .

+1

, , 2. , , , . , SaveForLaterOutput .

The library function itoa()(which translates as "integer to ASCII") (these days it has been replaced by a protected function _itoa_s()) allows you to specify the base in preparation for release.

+1
source

All Articles