简体   繁体   中英

int To String Representation of Fixed Length

I have a function that accepts a few integer params, and needs to convert then to ASCII string representation of a fixed length of 4. ie 4 becomes "0004" and 42 becomes "0042". It is safe to assume the params will be 0<=n<=9999

I could do that with something like:

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");
    ...
}

But that seems like more than I should need, especially if there are a lot of params to convert. is there a more efficient way to do this?

Edit: the goal is not to print the resulting strings.

Edit 2: something based around ss << std::setw( 4 ) << std::setfill( '0' ) << number; does what I need, thank you for the comments.

I think snprintf is a good candidate:

#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';
}

You can use std::ostringstream and treat it like an output stream:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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