0

I am trying to cast the value of a char(not the ASCII address) to size_t. I have succeeded but it feels like a lot of steps for something that seems to be straight forward (coming from C# background).

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main() {
    std::vector<size_t> singleDigits { 1, 4, 6, 8, 9 };
    std::string content = "1234";
    
    for (size_t j = 0; j < content.length(); j++) {
        std::string stringValue = std::string(1, content[j]);
        auto iterator = std::find(singleDigits.begin(), singleDigits.end(), (size_t)std::stoi(stringValue));
        if (iterator == singleDigits.end()) {
            std::cout << "Not found" << std::endl;
        } else {
            std::cout << stringValue << " was found" << std::endl;
        }
    }
}

So currently I am casting the char to string, cast the string to int and then cast the int to size_t. I am sure I am missing something obvious?

So my question is: What is the proper way to cast the char to size_t for the example above?

  • Are you trying to convert a string containing the decimal representation of a whole number into a vector of some integral type representing each decimal digit? E.g. from `std::string src{"9876"}` to `std::vector dst{9, 8, 7, 6}` or `std::vector dst{6, 7, 8, 9}`. – Bob__ Sep 02 '21 at 14:40
  • (The other step is casting to size_t.) – user202729 Sep 02 '21 at 14:44
  • Ok thanks. So I guess the most efficent way is: size_t val = (int)('5' - '0'); – Samuel Wahlberg Sep 02 '21 at 14:44

0 Answers0