Return two last digits of an integer as string in C

  • A+
Category:Languages

I have a 3 digit integer myInt:

int myInt = 809; 

I need an output string *myStr which consists of the 2 last digits. Therefore

char *mystr = "09"; 

What would be the easiest solution to do that?

 


You can do like this:

#include <stdio.h> #include <string.h>  int main(int argc, char **argv) {     char buf[32];     int myInt = 809;     char* mystr;     snprintf(buf, sizeof buf, "%d", myInt);     if (strlen(buf) > 2)         mystr = buf + strlen(buf) - 2;     else         mystr = buf;     fputs(mystr, stdout);     return 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: