int to String表示固定长度

时间:2014-07-07 18:59:26

标签: c++ string type-conversion

我有一个接受几个整数参数的函数,然后需要转换为固定长度为4的ASCII字符串表示。即4变为“0004”,42变为“0042”。假设参数将为0 <= n <= 9999

是安全的

我可以用以下的方式做到:

void foo(int a, int b) {
    std::string sa = std::to_string(a);
    std::string sb = std::to_string(b);

    for(int i = sa.length; i < 4; i++)
        sa.insert(0,"0");
    ...
}

但这似乎比我需要的更多,特别是如果有很多参数转换。有没有更有效的方法来做到这一点?

编辑:目标不是打印生成的字符串。

编辑2:基于ss << std::setw( 4 ) << std::setfill( '0' ) << number;的内容做了我需要的内容,感谢您的评论。

2 个答案:

答案 0 :(得分:1)

我认为snprintf是一个很好的候选人:

#include <cstdio>
#include <iostream>

int main() {
    char buffer[5];
    // Prints: 0001
    snprintf(buffer, 5, "%04d", 1);
    std::cout << buffer << '\n';
    // Prints: 1234 (not the 5)
    snprintf(buffer, 5, "%04d", 12345);
    std::cout << buffer << '\n';
}

答案 1 :(得分:1)

您可以使用std::ostringstream并将其视为输出流:

std::ostringstream ss;
ss << std::setw( 4 ) << std::setfill( '0' ) << number;
Send_To_Serial(ss.str().c_str());
相关问题