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?
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;
}
Here is a simple solution:
#include <stdio.h>
int main(void) {
char buf[3];
char *myStr;
unsigned int myInt = 809;
buf[0] = myInt / 10 % 10 + '0'; /* tens digit */
buf[1] = myInt % 10 + '0'; /* unit digit */
buf[2] = '\0'; /* null terminator */
myStr = buf;
puts(mystr);
return 0;
}
No pointer magic necessary here. Just use plain math (the remainder operator: %
), along with some suitable formatting:
#include <stdio.h>
int main(void)
{
char a[3]; /* 2 characters for any value >= 0 and < 100. So we rely on the 100 below.
+1 character for the `0`-terminator to make this a C-string*/
int i = 809;
assert(i >= 0);
sprintf(a, "%02d", i % 100);
puts(a);
}
or avoiding magic numbers:
#include <stdio.h>
long long power_integer(int base, int x)
{
if (0 == x)
{
return 1;
}
return base * power_integer(x - 1);
}
#define CUTOFF_BASE (10)
#define CUTOFF_DIGITS (2)
int main(void)
{
char a[3];
char f[8]; /* To hold "%01lld" to "%019lld".
(A 64 bit integer in decimal uses max 19 digits) */
int i = 809;
assert(i >= 0);
sprintf(f, "%%0%dlld*, CUTOFF_DIGITS);
sprintf(a, f, i % power_integer(CUTOFF_BASE, CUTOFF_DIGITS));
puts(a);
}
Output would be:
09
For the specific case of turning "magic numbers" into strings, you can as well do that at compile-time. That is, when you have an integer constant rather than a run-time value:
#include <stdio.h>
#define VAL 809
#define STRINGIFY(x) #x
#define STR(i) STRINGIFY(i)
#define SUBSTR(i, n) &(STRINGIFY(i))[n]
int main (void)
{
int whatever = VAL;
puts(STR(VAL));
puts(SUBSTR(VAL, 1));
return 0;
}
Output:
809
09
You could try something like this:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv){
int myInt = 809;
char buf[16]; // buffer big enough to hold the string representation
sprintf(buf, "%d", myInt); // write the string to the buffer
char* myStr = &buf[strlen(buf) - 2]; // set a pointer to the second last position
printf("myStr is %s\n", myStr);
return 0;
}