I need to print out a number that begins with 7, without the seven. For example, print 71011 as 1011 or 701 as 01. I've tried many techniques and just can't get it to work. Is there a printf format that will let me print out everything left of the decimal minus that very left number? I've also tried to make a string that will contain the 0's and 1's, but not the 7... it is not working however.

Any help would be greatly appreciated. Thanks

Recommended Answers

All 7 Replies

Use sprintf to convert the number to a string and then print all but the first character:

sprintf ( buffer, "%d", value );
puts ( &buffer[1] );

try the modulus operator %

ie

int x = (71011 % 70000);

and x = 1011

Thanks for the help guys, I finally got it working with the sprintf tip. The modulus wont work if my number starts with 0 however, learned that the hard way already, but thanks for the help!

>The modulus wont work if my number starts with 0
Your number won't start with 0 if you store it in an integer type. Leading zeros are ignored on formatted integer input and during integer processing. The only way to get the leading zero is to convert the number to a formatted string that specifies a field width and zero fill:

sprintf ( buffer, "%0*d", digits + 1, value );

The real problem with the remainder operator is that you're extracting the most significant digit, which involves finding the width of the number to create an appropriate mask if the value can have a variable number of digits:

#include <stdio.h>

int get_mask ( int value )
{
  int mask = 1;

  do {
    mask *= 10;
    value /= 10;
  } while ( value > 9 );

  return mask;
}

int main ( void )
{
  int value = 123;

  value %= get_mask ( value );
  printf ( "%d\n", value );

  return 0;
}

Alternative way from Narue:

// input your num here.
for (temp = num; temp > 9; temp /= 10)
  printf("%c", '0' + (temp % 10));

>Alternative way from Narue:
Maybe I missed something, but I don't think the original question included reversing the digits as well as trimming the most significant digit.

>Alternative way from Narue:
Maybe I missed something, but I don't think the original question included reversing the digits as well as trimming the most significant digit.

Sorry. Without much thinking, I jumped to answer this question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.