0

I am trying to port some feature from my password manager into c++ , but however I would like if its way to port this line of python to c++ equivalent. I wish to implement at least close to this 2 lines of code to c++

t = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
key = ''.join([secrets.choice(t) for _ in range(20)])
#include "common.h"
#include <iostream>

std::string Common::ascii_lowercase() {
    std::string ascii_lowercase;
    for (char c = 97; c <= 122; c++)
        ascii_lowercase += c;
    return ascii_lowercase;
}

std::string Common::ascii_uppercase() {
    std::string result;
    for (char c = 65; c <= 90; c++)
        result += c;
    return result;
}

std::string Common::digits(){
    std::string digits;
    for (int i = 0; i <= 9; i++) {
        digits += std::to_string(i);
    }
    return digits;
}

std::string Common::punctuation() {
    std::string punctuation;
    for (int i = 33; i <= 47; i++)
        punctuation += i;
    for (int j = 58; j <= 64; j++)
        punctuation += j;
    for (int z = 91; z <= 96; z++)
        punctuation += z;
    return punctuation;
}
zmrdim
  • 47
  • 3

1 Answers1

2

You can create a function join() that will take your sequence and the separator you want to use and return the same that the python method does.


Example:

std::string join(const std::vector<std::string> & sequence, const std::string & separator)
{
    std::string result;
    for(size_t i = 0; i < sequence.size(); ++i)
        result += sequence[i] + ((i != sequence.size()-1) ? separator : "");
    return result;
}

You can use it as follows:

std::vector<std::string> seq {"One", "Two", "Three", "Four"};
std::cout << join(seq, "--") << std::endl;

the output will be:

One--Two--Three--Four


Of course, you can use an other container than std::vector, it is just an example.

I hope it will help you.

Fareanor
  • 5,900
  • 2
  • 11
  • 37