是否可以将领先的零存储在int中

Is it possible to store a leading zero in an int?

本文关键字:存储 int 是否      更新时间:2023-10-16

我有一个编程分配,我需要在其中加密用户输入4位数INT。我将int分为四个单独的值,加密和解密功能有效。我的问题是,当我将四个单独的INT放回原处时,有些数字加密为零(例如: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;
    }

我的目标是返回加入(以零为零),而不仅仅是在功能中打印。

执行此操作:

#include <iomanip>
#include <iostream>
std::cout << std::setfill('0') << std::setw(4) << joined << std::endl;

int包含一个数字。它不包含任何特定的表示信息,例如是从包含一个或两个领先的零的文本中输入的,还是用十六进制,八分之一或鸡肉划痕编写的文本,甚至是通过添加一堆数字来计算的。这只是一个价值。

如果要显示带有领先零的int,则必须明确转换它:

char buf [20];
snprintf (buf, sizeof buf, "%04d", myint);  // output base 10, + leading zeros
                                           // for a field width of 4

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;
}

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

使用这种方法,如果您有一些不合理的数字,最终有多个领先的零,您将获得所有零。

,或者您可能需要具有将四个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;
}

这应该可以解决问题。

cout << setw(4) << setfill('0') << joined << endl;

为了使用这些操纵器,您需要:

#include <iomanip>

c 将 int存储为二进制号。但是,IO只是字符串。因此,要显示int,必须从int转换为字符串。在转换过程中,您可以从显示的数字中设置其中。为此目的,请使用流操纵器setwsetfill

相关文章: