简体   繁体   English

使用 printf("%s",&Buffer[i]); 在 C

[英]Using printf("%s",&Buffer[i]); in C

void Store(int temp){
    Buffer[i]=temp;
    i--;

}

int main(int argc, char *argv[]){
    Buffer[64]=00;

    int value = atoi(argv[1]);
    int base = atoi(argv[2]);

    char Table[16] = { '0', '1', '2', '3', '4', '5' , '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    //Mathmatical algorithm 
    while(value !=0){   
        digit = value%base;
        value = value/base;
        Store(digit);
        printf("%s",&Buffer[i]);
    }

I'm starting to learn C on my own.我开始自学C。 I'm trying to figure out how to use printf with this char Buffer[65].我正在尝试弄清楚如何将 printf 与这个字符缓冲区 [65] 一起使用。 Essentially, my algorithm pulls in a value and base given by the user, then calculates what that number is in that base.本质上,我的算法提取用户给定的值和基数,然后计算该基数中的数字。 If I change my printf to print out digit, it prints "123" for 57 base 4. So, I have it storing digit into the Buffer array in reverse (set int i to 63 because i set 64 to null).如果我更改我的 printf 以打印出数字,它会为 57 base 4 打印“123”。因此,我将数字反向存储到 Buffer 数组中(将 int i 设置为 63,因为我将 64 设置为 null)。

Long story short, when it stores into the buffer, increments down, then returns to the while loop it doesn't print any text.长话短说,当它存储到缓冲区时,递减,然后返回到 while 循环,它不打印任何文本。

Edit: As I'm looking around, it looks like printf only prints ascii characters.编辑:当我环顾四周时,看起来 printf 只打印 ascii 字符。 So I need to convert digit to one of the characters in Table[16]?所以我需要将数字转换为表 [16] 中的字符之一?

Here's a working answer, though it only works up to base 16:这是一个有效的答案,尽管它只适用于基数 16:

#include <stdio.h>
char Buffer[65];
int i = 63;

void Store(int temp){
    Buffer[i]=temp;
    i--;    
}

int main(int argc, char *argv[]){
    Buffer[64]=00;

    int value = atoi(argv[1]);
    int base = atoi(argv[2]);

    printf( "%d in base %d = ", value, base );

    char Table[16] = { '0', '1', '2', '3', '4', '5' , '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    //Mathmatical algorithm
    while(value !=0){
        int digit = value%base;
        value = value/base;
        Store( Table[digit]);  // or: Buffer[i--] = Table[digit];
    }
    printf("%s\n", &Buffer[i+1]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM