是否可以在int中存储前导零?

Joe*_*son 5 c++

我有一个编程任务,我需要加密4位int,由用户输入.我已将int拆分为四个单独的值,加密和解密函数可以工作.我的问题是当我将四个单独的整数重新组合在一起时,一些数字加密为零(例如:in:1234 out:0189)并且我想将输出存储到int中以供其他函数使用.

现在我有一个半生不熟的解决方案,如果第一个int为0,则首先打印0.

void joinInt(){
    if(int1 == 0) {cout << 0;}
    joined = int1 * 1000;
    joined += int2 * 100;
    joined += int3 * 10;
    joined += int4;
    cout << joined << endl;
    }
Run Code Online (Sandbox Code Playgroud)

我的目标是返回join(使用前导零)而不是仅仅在函数内打印它.

Ker*_* SB 5

做这个:

#include <iomanip>
#include <iostream>

std::cout << std::setfill('0') << std::setw(4) << joined << std::endl;
Run Code Online (Sandbox Code Playgroud)


Ric*_*ers 3

int 基本上存储前导零。您遇到的问题是您没有打印那里的前导零。

另一种不同的方法是创建一个函数,该函数接受四个 int 值和一个字符串,然后返回一个包含数字的字符串。

通过这种方法,您将拥有一个具有非常好的内聚性、无副作用、可在您需要完成类似操作的地方重用的辅助函数。

例如:

char *joinedIntString (char *pBuff, int int1, int int2, int int3, int int4)
{
    pBuff[0] = (int1 % 10) + '0';
    pBuff[1] = (int2 % 10) + '0';
    pBuff[2] = (int3 % 10) + '0';
    pBuff[3] = (int4 % 10) + '0';
    pBuff[4] = 0;                    // end of string needed.
    return pBuff;
}
Run Code Online (Sandbox Code Playgroud)

然后,在需要打印值的地方,您可以使用参数和提供的字符缓冲区调用函数,然后打印字符缓冲区。

通过这种方法,如果您有一些不合理的数字最终有多个前导零,您将得到所有零。

或者您可能想要一个将四个 int 组合成一个 int 的函数,然后使用另一个函数来打印带有前导零的组合 int 。

int createJoinedInt (int int1, int int2, int int3, int int4)
{
    return (int1 % 10) * 1000 + (int2 % 10) * 100 + (int 3 % 10) * 10 + (int4 % 10);
}

char *joinedIntString (char *pBuff, int joinedInt)
{
    pBuff[0] = ((joinedInt / 1000) % 10) + '0';
    pBuff[1] = ((joinedInt / 100) % 10) + '0';
    pBuff[2] = ((joinedInt / 10) % 10) + '0';
    pBuff[3] = (joinedInt % 10) + '0';
    pBuff[4] = 0;                    // end of string needed.
    return pBuff;
}
Run Code Online (Sandbox Code Playgroud)