Char 和 Int 在一个数组中
我想在一个数组中包含字符和整数。我想做的是在我的数组中包含 1 到 9,然后用户选择用字母 X 替换哪个数字。我该如何完成此操作?我假设我无法将字符传递到名为 int array[8];
的数组中那么有没有办法在数组中同时包含整数和字符?
I want to have chars and ints inside one array. What i am trying to do is have 1 to 9 in my array and the user selects which number to replace with the letter X. How can i have this done? I assume i cant pass chars into an array that is called as int array[8];
So is there a way to have both ints and chars in an array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
正如其他人提到的,当您使用
char
分配int[]
数组的元素时,char
将提升为int
> 价值观。当您从该数组中读取数据时,您必须使用显式强制转换。即,但是,以下内容
有效,
因为您需要跟踪哪些元素保存整数,哪些元素保存字符——这不是一个有吸引力的解决方案。
另一种选择是仅使用一个
char
数组并将数字 0..9 存储为字符。即“0”、“1”、..“9”。(第三个选项是让另一个变量将索引存储到“X”元素——但这与您的建议非常不同)
As others have mentioned,
char
will be promoted toint
when you assign elements of theint[]
array withchar
values. You would have to use an explicit cast when you are reading from that array.I.e., the following works
HOWEVER,
Since you would need to keep track of which elements hold ints and which hold chars -- this is not an attractive solution.
Another option is just have an array of
char
and store the digits 0..9 as chars. I.e., '0','1', ..'9'.(A third option is just have another variable store the index to the 'X' element -- but this is very different than what you are suggesting)
您可以将数字视为字符
You can treat your numbers as characters
最简单的解决方案是使用 -1 而不是 X,假设您的数组没有任何负数。我以前也这么做过。
The simplest solution is to use -1 instead of X assuming that your array does not have any negative numbers. I have done that before.
在 C++ 中,
int
和char
是几乎相同的东西。它们都以数字形式存储,只是分辨率不同。In c++
int
s andchar
s are almost the same thing. They are both stored as numbers, just with different resolutions.为什么不直接使用字符数组呢?
你可以做
Why don't you just use an array of characters?
You can do
这是一次黑暗中的刺探,因为用户模型和编程模型之间存在很大的区别。
当用户在指定索引处“插入”字符时,您希望更新 char 数组,而不是将值插入 int 数组中。保持 2 并排。
A stab in the dark, because there is a large distinction between the user-model and the programming model.
When the user 'inserts' a character at a specified index, you want to update an array of char instead of inserting the value in your int array. Maintain the 2 side-by-side.