For循环写特殊符号
void printchars()
{
for (x=128;x<224;x++)
write(x);
我希望 x 是 write 函数中的一个字符。如何更改写入函数将 x 视为 char,而不是循环中的 int?
void printchars()
{
for (x=128;x<224;x++)
write(x);
I want the x to be a char in the write function. How can i change the x to be treated by the write functions as a char, but an int in the loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只是想去掉它的范围,那么将
x
设为int
有何意义?这就是为什么这是一个非常奇怪的请求。您应该将x
设为unsigned char
--for(unsigned char x = 128; x <224; ++ x) { ....
如果您只是想确保调用
write<>
的unsigned char
模板特化,则可以这样调用:write( x);
如果没有,那么你将不得不使用类型转换:
write((unsigned char)x);
编辑:我刚刚意识到你可能会做什么正在经历。我的猜测是,您最初使用
char
但发现超过 127 的数字有问题。您可能应该使用unsigned char
作为x
而不是int
或char
。我编辑了我的答案以适应这一点。char
的范围是 -128 到 +127。unsigned char
的范围是 0-255。What is the point of making
x
anint
if you're just going to strip away its range? That's what makes this a very strange request. You should just makex
aunsigned char
--for(unsigned char x = 128; x <224; ++ x) { ...
.If you just want to ensure you're calling the
unsigned char
template specialization ofwrite<>
, then call it like this:write<unsigned char>(x);
If not, then you will have to use type casting:
write((unsigned char)x);
Edit: I just realized what you might be experiencing. My guess is that you originally used
char
but found something wrong with numbers over 127. You should probably be usingunsigned char
forx
instead of eitherint
orchar
. I edited my answer to accommodate this.char
has a range of -128 to +127.unsigned char
has a range of 0-255.将 x 转换为 char:
请注意,x 也可以是 char 作为循环计数器。
Cast x to a char:
Note that it is ok for x to be a char as the loop counter as well.