Trying to figure out how to output a phone number in c? - c

I am trying to input a phone number and print it out in this format (888)999-1111 format but when i am trying to print it out i get some weird output that is not what i am expecting to get back out. I am printing out the values of phone both in the input and in the print function bt they are different. The one in the input function is correct but it isnt correct in the print function. Thanks in advance for the help.
int phoneInput(void)
{
long int phone = 0;
printf("Input the politicians phone number with no speaces: ");
scanf("%ld", &phone);
printf("test : %ld", phone);
return phone;
}
int printPhone(long int phone)
{
int i = 10; //the number of digits in the phone
char output[11];
printf("Test: %ld", phone);
for (i = 0; i < 10; i ++)
{
while (phone > 0)
{
output[i] = phone % 10;
phone /= 10;
}
}
printf("- Phone number: (");
i = 0;
for (i = 0; i < 3; i++)
{
printf("%d", output[i]);
}
printf(")");
i = 3;
for(i = 3; i < 6; i++)
{
printf("%d", output[i]);
}
i = 6;
printf("-");
for(i = 6; i < 10; i++)
{
printf("%d", output[i]);
}
return 0;
}

The only reason you'd need to store a value as an int, a long int, or another numeric type is if you had to do arithmetic on it (unless it's required by a homework assignment specification). Don't be fooled by the fact that a phone number is composed of numbers - it makes most sense to be stored as a string!
If you can store the phone number as a string, you should:
char *phoneInput(void)
{
static char phone[100];
printf("Input the politicians phone number with no spaces: ");
fgets(phone, 100, stdin);
return phone;
}
Once you have that, it's easier to control how it is printed:
printf("(%.3s) %.3s-%.4s\n", phone, phone + 3, phone + 6);

A phone number should be stored as country, area, subscriber.
The example you gave would be 1 888 9991111
And note that any leading 00 for a country number is actually the local method of instructing the switch to dial an international number. In Spain it used to be 9 for a long time. The generic identification for international number dialing is now +.
See also https://www.internationalcitizens.com/international-calling-codes/

Sarah, first of all I would scan phone number as string, it is easier to do it that way. Another reason to scan it as string long int might not be sufficient enough, on some platforms long is 32 bits. But if you require 'long int` the best way would be:
printf ("(%ld)", number / 10000000); // prints area code (xxx)
printf (" %ld-", (number / 1000) % 1000); // prints xxx-
printf ("%ld\n", number % 10000); // prints xxxx\n
another way would be:
fscanf( stdin, " %3s%3s%4s", areacode, zone, number);
printf("(%s) %s-%s\n", areacode, zone, number);

In your existing code, the problem lies in the loops:
for (i = 0; i < 10; i ++)
{
while (phone > 0)
{
output[i] = phone % 10;
phone /= 10;
}
}
Your inner loop will keep executing without incrementing i causing the same position in the array to be written again and again.
i = 9;
do
{
output[i] = (phone % 10) + '0';
phone /= 10;
i--;
}while((phone > 0) && (i >= 0));
Please use "%c" in the printf while printing output.
List of issues in the code posted by OP. These are just issues in the
code posted by OP. The logic can be done in many other ways, but, this
answer purely focuses on issues in OP's code as-is:
phoneInput function should return long int instead of int
for and while loop - Two loops are not needed. This is the main error. This causes same position in array to be overwritten each time.
Loop counter for array position starts from 0, causing digits to be written in reverse order in the array
Since, you are using a char array, store and print char instead of int.
Complete code with issues fixed (as per OP's original code):
#include <stdio.h>
#include <string.h>
long int phoneInput(void)
{
long int phone = 0;
printf("Input the politicians phone number with no spaces: ");
scanf("%ld", &phone);
printf("test : %ld\n", phone);
return phone;
}
int printPhone(long int phone)
{
int i = 10; //the number of digits in the phone
char output[11];
memset(output, '0', sizeof(output));
printf("Test: %ld\n", phone);
i = 9;
do
{
output[i] = (phone % 10) + '0';
phone /= 10;
i--;
}while( (phone > 0) && (i >= 0));
printf("- Phone number: (");
i = 0;
for (i = 0; i < 3; i++)
{
printf("%c", output[i]);
}
printf(")");
i = 3;
for(i = 3; i < 6; i++)
{
printf("%c", output[i]);
}
i = 6;
printf("-");
for(i = 6; i < 10; i++)
{
printf("%c", output[i]);
}
return 0;
}
void main()
{
long int phone;
phone = phoneInput();
printPhone(phone);
}
Output:
Input the politicians phone number with no spaces: 8889991111
test : 8889991111
Test: 8889991111
- Phone number: (888)999-1111

I've made a few changes to your code. Please take a look.
long long int phoneInput(void)
{
long long int phone = 0;
printf("Input the politicians phone number with no speaces: ");
scanf("%lld", &phone);
printf("test : %lld", phone);
return phone;
}
int printPhone(long long int phone)
{
int i = 10; //the number of digits in the phone
char output[11];
printf("Test: %lld", phone);
i = 9; // removed for loop that was unnecessary.
while (phone > 0)
{
output[i] = phone % 10;
phone /= 10;
i--;
}
printf("- Phone number: (");
i = 0;
for (i = 0; i < 3; i++)
{
printf("%d", output[i]);
}
printf(")");
i = 3;
for(i = 3; i < 6; i++)
{
printf("%d", output[i]);
}
i = 6;
printf("-");
for(i = 6; i < 10; i++)
{
printf("%d", output[i]);
}
return 0;
}
int main(int argc, char const *argv[])
{
long long int n = phoneInput();
printPhone(n);
return 0;
}

void printTelephoneNumber(vector phoneNum) {
string phonePad[10] {
"000", "111", "ABC", "DEF", "GHI", "JKL", "MNO", "PRS", "TUV", "WXY"
};
size_t PHONE_NUMBER_LENGTH = phoneNum.size();
size_t LETTERS_PER_KEY = 3;
size_t maxcount = (size_t )pow(LETTERS_PER_KEY, PHONE_NUMBER_LENGTH);
// Could have used: colIndex[PHONE_NUMBER_LENGTH] = {0};
vector<int> letterIndex(PHONE_NUMBER_LENGTH, 0); // Use either name: colIndex or charIndex
for(int count=0; count<maxcount; count++) {
// print string
string str = "";
for(int i=0; i<PHONE_NUMBER_LENGTH; i++) {
str += phonePad[phoneNum[i]][letterIndex[i]];
}
cout << str << endl;
// Update next letter (column) indicies
int nextCount = count + 1; // next count
size_t i = PHONE_NUMBER_LENGTH - 1;
do {
letterIndex[i] = nextCount % LETTERS_PER_KEY;
nextCount = nextCount / LETTERS_PER_KEY;
i--;
} while(nextCount > 0);
}
}
Algorithm: There are 3^n combinations for n digits phone number. examples: phoneNum[n] = {2,3,4} => 3^3 = 27. Use extra space for tracking letters in a digit => letterIndex[PHONE_NUMBER_LENGTH]

while (phone > 0)
{
output[i++] = (phone % 10) + '0';
phone /= 10;
}
and
printf("%c", output[i]);
are the changes that need to be made in your code to make it work.
The first change (+ '0') is to convert from int to char.
The second one is because you want to print a char and not an int.
I advise you to check the manual of printf and the ascii table to understand better.

Related

Can we scanf an array?

I want to input an array of integers then print out the even numbers from the inputted numbers..
example is if I input 2466688992,
it will output 24666882;
I have a my code below:
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter array of numbers: ");
scanf("%d",&a);
for(i=0; i<sizeof(a); i++){
if(a[i]%2==0)
printf("%d",a[i]);
}
getch();
return 0;
}
It resulted into garbage : 2468000075416640419940000004225568000
This is the function that prints even numbers in an integer :
#include<stdio.h>
int main(){
int num,rem,even=0,digit;
printf(" Enter an integer number: ");
scanf("%d",&num);
printf("\n The even digits present in %d are \n",num);
while(num>0){
digit = num % 10;
num = num / 10;
rem = digit % 2;
if(rem == 0)
even++;
printf("\n %d.",digit);
}
return 0;
}
You should scan the array as a string (unless you want to impose the number of items in the array), and then parse the string to store the different numbers:
long a[50];
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
int j = 0;
for (int i = 0; i < len; ) {
long sign = 1;
long n = 0;
if (buf[i] == '+') {
++i;
}
else if (buf[i] == '-') {
sign = -1;
++i;
}
if (isdigit(buf[i])) {
while (isdigit(buf[i])) {
n = 10 * n + buf[i++] - '0';
}
a[j] = n * sign;
}
else
i++;
}
for (int i = 0; i < j; i++)
if (!(a[i] ℅ 2)) // true if even
printf("%ld ", a[i]);
This will store all your digits in your array a of size j.
Edit: if you are talking about digits then its easier:
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
for (int i = 0; i < len; i++)
if (isdigit(buf[i]) && !((buf[i] - '0') ℅ 2)) // true if even, note that '0' equals 0x30 so there is no need to sub it to check for odd/even in reality.
printf("%c ", buf[i]);

How to convert integer to string with plus and minus

I need to get an integer form the user and put the number in array of chars with "+" or "-"
and it print only + and not - if the number is under zero, and it not print the numbers that the user put at all
if can someone tell me what is the problem in my code?
Thank you
int main()
{
int number = 0, i = 0;
char numberArray[MAX_LEN] = {0};
int length = 0;
int save = 0;
int j = 0;
printf("Enter num: ");
scanf("%c", &number);
if(number >= 0)
{
numberArray[i] = '+';
}
else
{
numberArray[i] = '-';
}
save = number;
length = findLength(number);
number = save;
j = length;
for(i = 1; i <= length; i++)
{
numberArray[j] = number % 10;
number /= 10;
j--;
}
printf("%s", numberArray);
}
int findLength(int number)
{
int length = 0;
while(number > 0)
{
number /= 10;
length++;
}
return length;
}
int main(void)
{
int number;
char number_str[10];
scanf("%d", &number);
sprintf(number_str, "%+d", number);
printf("%s\n", number_str);
}
To read your binary integer:
printf("Enter num: ");
scanf("%d", &number);
To print with +/-:
printf ("%+d\n", number);
To write the formatted integer to a string:
sprintf (numberArray, "%+d\n", number);
Here is a good reference for printf format strings:
http://www.cplusplus.com/reference/cstdio/printf/
scanf("%c", &number);
will give you the ASCII value of one char given in the input, that's why the numbers that printed aren't those you write.
you should change it to
scanf("%d", &number);
this way it will get the right input
if (number < 0) {
printf("%d", -number);
} else {
printf("+%d", number);
}
should suffice. Let the standard library routines do their work.

How to convert hexadecimal to decimal in C?

So, with my beginner level of experience in C I've been trying to write a code that converts hexadecimal input to a decimal with an array. I believe you will get it more spesificly by looking at my code but it does not work properly. I keep getting an amount that is much larger than intended.
#include <stdio.h>
int main()
{
int i, k, j, N, power, result;
char array[50];
result = 0;
printf("how many charecters are there in your hexadecimal input?: \n");
scanf("%d", &N);
for(k=0; k<=N-1; k++)
{
printf("What is the %d . value of your hexadecimal input?: \n", k+1);
scanf("%s", &array[k]);
}
for(i=0; i<=N-1; i++)
{
power = 1;
for(j=0; j<=i; j++)
{
power = power *16;
}
if((array[i] >= 0) && (array[i] <= 9))
{
result = result + array[i] * power;
}
else
{
result = result + (array[i] - 'A' + 10) * power;
}
}
printf("your result is %d", result);
return 0;
}
Your code is overly complicated and wrong, but the idea is correct.
You want this:
#include <stdio.h>
#include <string.h>
int main()
{
char array[50];
scanf("%49s", array); // just use a single scanf with %s
// "49s" will avoid buffer overflow of array
int length = strlen(array); // get length of string (and use meaningful
// variable name length instead of N)
int result = 0;
for (int i = 0; i < length; i++)
{
int nibble; // nibble is the hexadécimal "digit" from 0 to 15
if ((array[i] >= '0') && (array[i] <= '9'))
{
nibble = array[i] - '0';
}
else
{
nibble = array[i] - 'A' + 10;
}
result *= 16; // no need to maintain power, just multiply by 16
// on each run
result += nibble; // ... and add the nibble
}
printf("your result is %d", result);
return 0;
}
There is still room for improvement:
you should accept lowercase
there is no test for invalid characters such as 'G', 'H' etc.
you should put the conversion code in a function such asint HexStringToDecimal(const char *hexstring)
and certainly a bunch of other things I forgot.
Exercise for you: convert that code so it converts a decimal string instead of a hexadecimal string. Hint: the code will be simpler.
Side note:
Avoid constructs like this:
for(k=0; k<=N-1; k++)
instead use this exact equivalent which is more readable:
for(k=0; k<N; k++)
just edited your code a little bit,
and also the input is supposed to be from left to right
instead of right to left according to which I think you have coded.
Hence, for C6, first C then 6.
#include <stdio.h>
int main()
{
int i, k, j, N, power, result;
char array[50];
result = 0;
printf("how many charecters are there in your hexadecimal input?: \n");
scanf("%d", &N);
for(k=0; k<=N-1; k++)
{
printf("What is the %d . value of your hexadecimal input?: \n", k+1);
scanf(" %c", &array[k]);
}
for(i=0; i<=N-1; i++)
{
power = 1;
for(j=0; j<=N-2-i; j++)
{
power = power*16;
}
if((array[i] >= '0') && (array[i] <= '9'))
{
result = result + (array[i] - '0') * power;
}
else
{
result = result + (array[i] - 'A' + 10) * power;
}
}
printf("your result is %d", result);
return 0;
}
the takeaways
your input taking is inefficeient. and in that too %c instead of %s in scanf.
if((array[i] >= 0) && (array[i] <= 9)), suppose i=1 and array[1] = 7. Now, you are comparing ascii value of 7 which is 55, instead of 7.
same thing in the statement of if, the ascii values of array[i] are being used so I have subtracted accordingly.

how to extract the even number from user input, and combine them as a new number in C program

test case:
input: 1234
output: 24
input: 2468
output: 2468
input: 6
output: 6
I have this code:
#include <stdio.h>
#include <math.h>
int main() {
int num;
printf("Enter a number: \n");
scanf("%d", &num);
int numberLength = floor(log10(abs(num))) + 1;
int inputNumberArray[numberLength];
int evenNumberCount = 0;
int even[10];//new even no. array
int i = 0;
do {
inputNumberArray[i] = num % 10;
num = num / 10;
i++;
} while (num != 0);
i = 0;
while (i < numberLength) {
if (inputNumberArray[i] % 2 == 0) {
evenNumberCount ++;
even[i] = inputNumberArray[i];
}
i++;
}
printf("array count %d\n", evenNumberCount);
i = 0;
for (i = 0; i < 8; i++) {
printf(" %d", even[i]);//print even array
}
i = 0;
int result = 0;
for (i = 0; i < 10; i++) {
if (evenNumberCount == 1) {
if (even[i] != 0) {
result = even[i];
} else {
break;
}
} else {
if (even[i] != 0) {
result = result + even[i] * pow(10, i);
} else
break;
}
}
printf("\nresult is %d", result);
/*
int a = 0;
a = pow(10, 2);
printf("\na is %d", a);
*/
}
when I enter number 1234, the result/outcome is 4, instead of 24.
but when I test the rest of test case, it is fine.
the wrong code I think is this: result = result + even[i] * pow(10, i);
Can you help on this?
Thanks in advance.
why do you have to read as number?
Simplest algorithm would be
Read as text
Validate
loop through and confirm if divisible by 2 and print live
next thing, have you try to debug?
debug would let you know what are doing wrong. Finally the issue is with indexing.
evenNumberCount ++; /// this is technically in the wrong place.
even[i]=inputNumberArray[i]; /// This is incorrect.
As the user Popeye suggested, an easier approach to accomplish this would be to just read in the entire input from the user as a string. With this approach, you can iterate through each letter in the char array and use the isdigit() method to see if the character is a digit or not. You can then easily check if that number is even or not.
Here is a quick source code I wrote up to show this approach in action:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char input[100] = { '\0' };
char outputNum[100] = { '\0' };
// Get input from user
printf("Enter a number: ");
scanf_s("%s", input, sizeof(input));
// Find the prime numbers
int outputNumIndex = 0;
for (int i = 0; i < strlen(input); i++)
{
if (isdigit(input[i]))
{
if (input[i] % 2 == 0)
{
outputNum[outputNumIndex++] = input[i];
}
}
}
if (outputNum[0] == '\0')
{
outputNum[0] = '0';
}
// Print the result
printf("Result is %s", outputNum);
return 0;
}
I figured out the solution, which is easier to understand.
#include <stdio.h>
#include <math.h>
#define INIT_VALUE 999
int extEvenDigits1(int num);
void extEvenDigits2(int num, int *result);
int main()
{
int number, result = INIT_VALUE;
printf("Enter a number: \n");
scanf("%d", &number);
printf("extEvenDigits1(): %d\n", extEvenDigits1(number));
extEvenDigits2(number, &result);
printf("extEvenDigits2(): %d\n", result);
return 0;
}
int extEvenDigits1(int num)
{
int result = -1;
int count = 0;
while (num > 1) {
int digit = num % 10;
if (digit % 2 == 0) {
result = result == -1 ? digit : result + digit * pow(10, count);
count++;
}
num = num / 10;
}
return result;
}
}
You are overcomplicating things, I'm afraid.
You could read the number as a string and easily process every character producing another string to be printed.
If you are required to deal with a numeric type, there is a simpler solution:
#include <stdio.h>
int main(void)
{
// Keep asking for numbers until scanf fails.
for (;;)
{
printf("Enter a number:\n");
// Using a bigger type, we can store numbers with more digits.
long long int number;
// Always check the value returned by scanf.
int ret = scanf("%lld", &number);
if (ret != 1)
break;
long long int result = 0;
// Use a multiple of ten as the "position" of the resulting digit.
long long int power = 1;
// The number is "consumed" while the result is formed.
while (number)
{
// Check the last digit of what remains of the original number
if (number % 2 == 0)
{
// Put that digit in the correct position of the result
result += (number % 10) * power;
// No need to call pow()
power *= 10;
}
// Remove the last digit.
number /= 10;
}
printf("result is %lld\n\n", result);
}
}

two-digit string addition with no number at the end

I have to add two digit strings, meaning 1234 12+34 (at least that's what i gather). I wrote a program that does this expect for one exception, that is when the last number doesn't have a pair it wont add properly.
Here is the code i have:
void main()
{
char string[1000];
int count,sum=0,x,y;
printf("Enter the string containing both digits and alphabet\n");
scanf("%s",string);
for(count=0;count < string[count]; count++)
{
x=(string[count] - '0') * 10;
y=(string[count+1] - '0') + x;
sum += y;
count++;
}
printf("Sum of string in two digit array is =%d\n",sum);
}
so basically if i have 123 the program does 12+(30-48), instead of 12+3. Ive been sitting on it for a while, and cant figure out how to fix that issue, any tips or advice would be welcomed.
(Strings like 1234 or 4567 will do 12+34 and 45+67)
#include <stdio.h>
#include <ctype.h>
int main(void){
char string[1000];
char digits[3] = {0};
int i, j, x, sum = 0;
printf("Enter the string containing both digits and alphabet\n");
scanf("%999s", string);
for(j = i = 0; string[i]; ++i){
if(isdigit(string[i])){
digits[j++] = string[i];
if(j==2){
sscanf(digits, "%d", &x);
sum += x;
j = 0;
}
}
}
if(j==1){
digits[j] = 0;
sscanf(digits, "%d", &x);
sum += x;
}
printf("Sum of string in two digit array is = %d\n", sum);
return 0;
}

Resources