是否可以将领先的零存储在int中
Is it possible to store a leading zero in an int?
我有一个编程分配,我需要在其中加密用户输入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
转换为字符串。在转换过程中,您可以从显示的数字中设置其中。为此目的,请使用流操纵器setw
和setfill
。
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 如果 x < 10,则添加前导 0 并将其存储为 int
- 如何读取 TXT 文件并仅将 int 存储在 C 中
- 如何在函数中将字符串和分数存储为(Int 或 float)
- 如何声明一个必须在C++中同时存储int和char值的2D数组
- 如果char可以在C++中存储数字,为什么我们需要int
- 如果我在 C++ 中为 int 提供双精度,输入缓冲区中存储了什么?
- 我应该使用无符号字符而不是 int 来存储永远不会大于 255 的值吗?
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- unordered_set是否适合存储矢量<int>元素的数据结构?如果是这样,我将如何实现哈希函数?
- 什么是在C 中存储结果INT*的最佳数据类型
- char*中存储的返回int值(0-255)给出了负值
- 将字符指针按顺序存储在 map 中 std::map<char*, int> mymap。将其存储为字符或字符串不是一个选项
- 如何在文件中节省空间地存储和检索 std::vector<int> 值
- 将INT和STR输入并将它们存储到两个单独的列表中
- 如何在单个变量中同时存储 int 或字符串,而不会丢失它们的类型
- 在数组中存储 int 的各个数字
- 如何将 void 指针类型转换为 int 指针,然后在其中存储 int