我有一个函数 PutChar(int, int, char)
可以在给定的行和列中打印出给定的字符。如果我向它传递一个字符,这个函数就可以正常工作。我还希望能够将 0-9 范围内的 int 传递给函数并让它打印实际的 int 值。例如,我希望以下代码打印 int x 的实际值:
int x = 5;
PutChar(1, 1, x);
void PutChar(int row, int col, char ch) {
char str[20];
sprintf(str, "\e[%d;%dH", row, col); // move cursor to row-col
write(1, str, strlen(str));
write(1, &ch, 1);
}
在将 int 传递给函数时,我尝试转换为 char,但它打印出奇怪的字符。
编辑: 可以打印的整数范围是 0-9。这是家庭作业,所以我不能更改函数的原型(prototype)。
最佳答案
如果您应该使用 PutChar()
函数输出单个数字,通过添加 '0'
,如 Shan 所建议的:
PutChar(1, 1, x + '0');
如果您要修改 PutChar()
函数以在传递小整数时输出数字,也可以这样做。
假设您的终端支持 ASCII 或某些基于 ASCII 的编码,例如 Latin1 或 UTF-8,则 32(空格)以下的字符是控制字符。将它们放在屏幕上的给定位置没有多大意义。因此,您可以修改 PutChar()
以专门处理 0
和 9
之间的 char
值,而不会与当前行为冲突在实际的 ASCII 字符 32 及以上(如果 char
被签名,甚至是负数):
void PutChar(int row, int col, char ch) {
char str[20];
sprintf(str, "\e[%d;%dH", row, col); // move cursor to row-col
write(1, str, strlen(str));
if (ch >= 0 && ch <= 9)
ch += '0'; // convert small integer to digit
write(1, &ch, 1);
}
void Test(void) {
for (int x = 0; x < 10; x++) {
PutChar(x + 1, x + 1, x);
}
}
另请注意,您的程序是不安全的:sprintf
将导致 row
和 col
的大值发生缓冲区溢出。您应该使用 snprintf()
和更大的缓冲区。你可以进一步简化代码,只调用一次write
:
void PutChar(int row, int col, char ch) {
char str[46];
int len;
if (ch >= 0 && ch <= 9)
ch += '0'; // convert small integer to digit
len = snprintf(str, sizeof str, "\e[%d;%dH%c", row, col, ch);
if (len > 0)
write(1, str, len);
}
关于c - 传递给接受 char 参数的函数时打印 int 的实际值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29764180/