首页 > 解决方案 > 如何在 C 中使用 write() 函数编写整数?

问题描述

我是 C 的菜鸟,并试图使用write()函数来显示整数。

这是我的代码:

int n = 7;
write(1, &n, 4);

我想显示7,但是当我设置n为大数字时,程序什么也不显示或显示其他奇怪的字符。

我错过了什么?

标签: cintegercommand

解决方案


像这样的对象int在内存中用各种位表示。该write例程将这些内存位准确地传输到其目的地。

终端并非旨在显示任意内存位。他们不会将这些位解释为一个int或其他对象,然后显示该解释。通常,我们将字符传输到终端。更具体地说,我们发送代表字符的代码。终端设计用于接收这些代码并显示书写的小图片(字符、字形、表情符号等)。

要让终端显示“7”,我们需要向其发送“7”的代码。字符的通用代码系统是 ASCII(美国信息交换标准代码)。“7”的 ASCII 码是 55。所以,如果你这样做:

char x = 55;
write(1, &x, 1);

如果使用 ASCII,则终端将在其显示屏上绘制“7”。

用于显示值以供人类阅读write的错误例程也是如此。int相反,您通常使用printf,如下所示:

printf("%d", n);

finprintf代表formatted. _ 它检查表示值的位n并将表示的值格式化为供人类阅读的字符,然后将这些字符写入标准输出。

If you want to use write to transmit characters to the terminal, you can use sprintf to get just the formatting part of printf without the printing part. For starters, this code will work:

char buffer[80];                            // Make space for sprintf to work in.
int LengthUsed = sprintf(buffer, "%d", n);  // Format n in decimal.
write(1, buffer, LengthUsed);               // Write the characters.

(More sophisticated code would adapt the buffer size to what is needed for the sprintf.)


推荐阅读