C++ get each digit in int

前端 未结 13 1332
谎友^
谎友^ 2020-12-02 21:50

I have an integer:

int iNums = 12476;

And now I want to get each digit from iNums as integer. Something like:

foreach(iNum          


        
13条回答
  •  死守一世寂寞
    2020-12-02 22:10

    I don't know if this is faster or slower or worthless, but this would be an alternative:

    int iNums = 12476;
    string numString;
    stringstream ss;
    ss << iNums;
    numString = ss.str();
    for (int i = 0; i < numString.length(); i++) {
        int myInt = static_cast(numString[i] - '0'); // '0' = 48
        printf("%i-", myInt);
    }
    

    I point this out as iNums alludes to possibly being user input, and if the user input was a string in the first place you wouldn't need to go through the hassle of converting the int to a string.

    (to_string could be used in c++11)

提交回复
热议问题