【问题标题】:Converting int to string without printing [duplicate]将int转换为字符串而不打印[重复]
【发布时间】:2014-06-20 18:57:20
【问题描述】:

我想将 int 转换为字符串,而不在屏幕上打印任何内容。现在我使用了 sprintf,但这也将 int 打印到我的屏幕上。 我的编译器也不支持 itoa,所以我也不能使用它。

【问题讨论】:

  • 请出示您的代码。通常sprintf 不会“打印到屏幕”,所以你必须添加一些东西。如果您为您的编程语言添加标签也会有所帮助。

标签: string int


【解决方案1】:

我假设您使用 ANSI C。

您不能使用itoa,因为它不是标准函数。

sprintfsnprintf 致力于此。

由于您不想使用sprintf,请改用自己的itoa

#include <stdio.h>

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

原答案:here

【讨论】:

    猜你喜欢
    • 2015-06-18
    • 2017-05-07
    • 1970-01-01
    • 2012-01-24
    • 2013-11-04
    • 2021-12-25
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多