Owen Stafford
Owen Stafford

Reputation: 31

Split int into 2 parts in C

Im looking to have the user input a 7 digit Int, which I have already done.

I have an Int value with 7 digits, and I would like to add a hyphen after the 3rd digit (turn it into a phone number format)

The way I want to do this is by having the system create 1 new Int that is equivalent to the first 3 digits of the initial Int, then a second one equivalent to the last 4 digits. Then printf with the hyphen in between

int phoneNumber;

scanf

phoneNumber = 1234567

int 1pNum = 123

int 2pNum = 4567

printf(1pNum + "-" + 2pNum)

Don't worry, I know the format in which i explained that would not work exactly, I just want to know how to split it

Upvotes: 0

Views: 1919

Answers (2)

maerics
maerics

Reputation: 156434

#include <stdio.h>

int main(void)
{
  int phoneNumber = 1234567;
  int p1 = phoneNumber / 10000;
  int p2 = phoneNumber % 10000;
  printf("OK: %03d-%04d\n", p1, p2);
  // OK: 123-4567
  return 0;
}

Upvotes: 1

Mia
Mia

Reputation: 381

A clean code for this problem would be to convert it to string and insert hyphen in 4th character. Assuming you are using c: first part is from int to string you can use code like (http://www.cplusplus.com/articles/D9j2Nwbp/)

 template <typename T>
   string NumberToString ( T Number )
 {
    ostringstream ss;
    ss << Number;
    return ss.str();
 }

and for second part you can use .insert like:

strNumber.insert(4, "-");

Upvotes: 0

Related Questions