Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Programming language C: Converting int to string?
I need to to write a program that converts an integer to a string, with determined length (L) and to put zeros if there are any spaces before the integer. (example: If the user gives the number 4437 and L=7, than the result will be '0004437') Any help???
I guess I should use itoa(). But since I am pretty new in C, I need some help!
3 Answers
- McFateLv 79 years agoFavorite Answer
You can use sprintf.
For example, if L=8, then a format string of "%08d" will print eight digits with leading zeroes. You can use another sprintf to construct the format string:
char fmt[10];
char res[10];
sprintf(fmt, "0%dd", L ); // Create %0[L]d format string
sprintf(res, fmt, yourNumber ); // Use the format
@M
- ?Lv 45 years ago
your application seems to basically be changing a single digit of decimal into hexadecimal (form of extra of merely renaming 10 - 15 A - F) particularly than going from hexadecimal to decimal in case you had to bypass from hexadecimal to decimal you need to do some thing alongside the lines of int A = 10, B = 11, ...; then take the enter that they provide you and then have cin >> hexa; n = digit; deci += hexa * pow(sixteen, n); utilising a loop to verify you get each and every digit or some thing in case you already know the type of digits you are able to start from the utmost one or you're able to desire to start from the backside one till you go with for to get the entire enter first
- rogerLv 79 years ago
sprintf is your friend in this case
http://www.cplusplus.com/reference/clibrary/cstdio...
look up the 0 specifier in flags and * in the width specifiers
this is an easy example:
#include <stdio.h>
int main(void){
int j=4437;
int L;
L=7;
char res[20];
sprintf(res,"%0*d",L, j);
printf("%s",res);
return 0;
}