I have a problem with a program that should split a phone number(ex. 1231231234) that user enters into three groups and display them like this (123)-123-1234. I'm not sure how to split this number and what to use in order to complete it. I didn't completed the code party but here's what i got.
#define SIZE 3
int main(void){
int option, j;
int phList = 0;
int phoneNum[SIZE];
printf("---=== Phone Numbers ===---\n");
while(1){
printf("\n");
printf("1. Display Phone List\n");
printf("2. Add a Number\n");
printf("0. Exit\n");
printf("\n");
printf("Please select from the above options: ");
scanf("%d", &option);
if(option == 0){
printf("Exiting Phone Number App. Good Bye!!!\n");
return 0;
}
if(option == 1){
printf("\n");
printf("Phone Numbers\n");
printf("==============\n");
for(j = 0; j < phList; j++){
printf("\n", phoneNum[j]);
}
}
if(option == 2){
if(phList < SIZE){
printf("\n");
printf("Add a Number\n");
printf("============\n");
scanf("%d", &phoneNum[phList]);
phList++;
} else {
printf("Add a Number\n");
printf("============\n");
printf("ERROR!!! Phone Number List is F$
}
}
}
return 0;
}
I would consider using fgets() to get the phone number as a string, rather than getting it as an integer. Then you can filter the input so that only the digits are kept, allowing users to enter parenthesis, spaces, or dashes as desired. Finally, sscanf() can be used to scan the filtered string into three strings for the area code, exchange number, and subscriber number. If you like, these strings can be converted to numbers by atoi() or strtol().
The OP seems to be assuming that the phone number follows the format of the North American Numbering Plan, but phone number formats may differ. The string representation is more flexible than an integer representation, making future modifications to the code easier.
Here is an example of how this might be done:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void filter_num(char *str);
int main(void)
{
char buffer[1000];
char area_code[4];
char xch_num[4];
char sub_num[5];
printf("Enter phone number: ");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
fprintf(stderr, "Error in fgets\n");
exit(EXIT_FAILURE);
}
filter_num(buffer);
if (sscanf(buffer, "%3s%3s%4s", area_code, xch_num, sub_num) != 3) {
fprintf(stderr, "Phone number format error\n");
exit(EXIT_FAILURE);
}
printf("Phone number is: (%s) %s-%s\n",
area_code, xch_num, sub_num);
return 0;
}
void filter_num(char *str)
{
char *p = str;
while (*p != '\0') {
if (isdigit(*p)) {
*str++ = *p;
}
++p;
}
*str = '\0';
}
I will suggest defining a function to split the number and display that, Please have a look on this one, I have written it for you just now and works fine:
void DisplayNum(long long int PhNum)
{
printf("\n ");
for(int i=1; i<=10; ++i) // Since Phone Number Contains 10 digits
{
int digit= PhNum/(pow(10,10-i)); // Spliting digits
digit= digit%10;
if(i==1)
{
printf(" (");
}
if(i==4)
{
printf(")-");
}
if(i==7)
{
printf("-");
}
printf("%d",digit); // Displaying Digits
}
}
But make sure to use #include<math.h> at the beginning because i am using pow() function here. Then you can just pass each Phone Number in array to display to this function. The for-loop to display each Phone Number in array will be like :
for(j = 0; j < phList; j++){
DisplayNum(phoneNum[j]);
}
Related
I'm trying to work on a program to input a phone number and test if it is the right amount of digits in C, also checking if the first value is not 0 or 1. Scanf is not taking a value when I enter it and I do not understand why. If someone could please point out to me what the issue is it'd be much appreciated.
#include <stdio.h>
int main (void){
int number = 0;
int loop = 0;
while(loop == 0){
printf("Enter a phone number: ");
scanf(" %d ", &number);
printf("%d", number);
int firstDigit;
while(number >= 10){
firstDigit = number/10;
}
if((number/1000000) >= 1 && (number/1000000) < 10){
if(firstDigit == 1){
printf("Invalid central office code: 1");
}
else if(firstDigit == 0){
printf("Invalid central office code: 0");
}
else{
int firstThree = (number/10000);
int lastFour = (number%10000);
printf("%d - %d", firstThree, lastFour);
}
}
else if(number == 0){
printf("Exiting.");
loop = 1;
}
else{
if((number/1000000)>=10){
printf("Invalid phone number: too many digits");
}
else if((number/1000000)<1){
printf("Invalid phone number: too few digits");
}
}
}
return 0;
}
This:
while(number >= 10) {
firstDigit = number/10;
}
is an infinite loop, because you are not modifying number.
What you probably want to do is:
while(number >= 10) {
firstDigit = number/10;
number /= 10;
}
You should avoid scanf() to read input. Better use fgets(), and then sscanf() for parsing.
char input[1024]; // This should be large enough
if (!fgets(input, sizeof input, stdin)) {
printf("Input error\n");
return 1;
}
input[strcsnp(input, "\n")] = '\0'; // Because fgets reads \n so remove it
if (sscanf(input, "%d", &number) != 1) {
printf("Parsing error\n");
return 1;
}
// Use number...
Also, scanf() and sscanf() "ignore" the first 0s you type as part of the phone number, so your solution might not be correct. The best way to represent a phone number is either by storing it as a string (as mentioned in a comment), or by defining a phone number structure.
Int size in c is 4 bytes, which can hold values only -2,147,483,648 to 2,147,483,647.
It can't store all 10 digit values.
you can use long
long number = 0;
scanf("%ld", &number);
printf("%ld", number);
I am a beginner in C programming and I am stuck in my little program .
I just wanna make a list from which I ask users to select a number from that list. Then the program should do what it should be done.
My list is:
Create a table
Max & Min Number Checking
Negative & Positive Number Checking
Ascending Order
Descending order
Exit
I couldn't start correctly! When I first press 1 to create the table, the program keeps looping again and again!!
I want my program to ask me for some values then take my value and draw me a table and then store these values temporary in memory, so that I can execute the rest of commands from my list.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int t[100],n,a,f,s=0,i,max,min,m,l;
{
printf("Welcome to My simple Math Program in C language \n");
printf("1:Create a table\n 2:Max&Min Number Checking\n 3:Negative&Positive Number Checking\n 4:Ascending Order\n 5:Descending ordert\n 6:Exit\n ");
printf("Please Choose a number from the list" );
scanf("%d",&a);
while(a!=6){
switch(a){
case 1:printf("Please Enter The Length Of Your Table ");
scanf("%d",&n);
printf("Please Enter Your Table Elements ");
for(int i=0;i<n;i++){
scanf("%d",&t[i]);
}
for(int i=0;i<n;i++){
printf("%d ",t[i]);
}
break;
case 3:
if(t[i]<0){
printf("This Number is Negative %d",t[i]);
}
else if(t[i]==0){
printf("This Number is nulle %d",t[i]);
}
else
{
printf("This Number is Positive %d",t[i]);
}
;break;
case 6:
break;
}
}
return 0;
}
}
Your scanf() statement is outside your while loop so it is only executed once. You need something like this:
do
{
scanf("%d",&a);
...rest of code
} while (a!=6)
You should print the message and read the option inside the main loop:
#include <stdio.h>
#include <stdlib.h>
int main() {
int t[100], n, a, f, s = 0, i, max, min, m, l;
printf("Welcome to My simple Math Program in C language\n");
for (;;) {
printf("1: Create a table\n"
"2: Max&Min Number Checking\n"
"3: Negative&Positive Number Checking\n"
"4: Ascending Order\n"
"5: Descending ordert\n"
"6: Exit\n");
printf("Please Choose a number from the list: ");
if (scanf("%d", &a) != 1) /* invalid input */
break;
if (a == 6)
break;
switch (a) {
case 1:
printf("Please Enter The Length Of Your Table ");
if (scanf("%d", &n) != 1)
break;
if (n > 100)
n = 100;
printf("Please Enter Your Table Elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &t[i]);
}
for (i = 0; i < n; i++) {
printf("%d ",t[i]);
}
break;
case 3:
i = 0;
if (t[i] < 0) {
printf("This Number is Negative %d\n", t[i]);
} else
if (t[i] == 0) {
printf("This Number is null %d\n", t[i]);
} else {
printf("This Number is Positive %d",t[i]);
}
break;
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#define mL 5
#define NL 20
#define UL 6
struct LIST
{
char n[NL];
float am;
char u[UL];
};
struct array
{
struct LIST array;
};
void addCityInformation(struct array *add, int *items);
void printCities(struct array *all, int items);
int main(void)
{
struct array shopping[mL];
int choice, nrOfItemsAdded = 0;
do
{
printf("\nWhat du you want to do?");
printf("\n1 - add grocery");
printf("\n2 - print shopping list");
printf("\n3 - exit");
printf("\nYour choice: ");
scanf("%d", &choice);
while(getchar() != '\n');
switch (choice)
{
case 1:
addCityInformation(&shopping[nrOfItemsAdded], &nrOfItemsAdded);
break;
case 2:
printCities(shopping, nrOfItemsAdded);
break;
case 3:
printf("Exiting program\n\n");
break;
default:
printf("Invalid input\n\n");
break;
}
}
while(choice != 3);
return 0;
}
int clean_stdin()
{
while (getchar()!='\n');
}
void addCityInformation(struct array *add, int *items)
{
if(*items == mL)
printf("No more space in the list\n");
else
{
printf("Enter name: ");
fgets(add->array.n, NL, stdin);
add->array.n[strlen(add->array.n)-1] = '\0';
do {
printf("Enter amount: ");
}while (scanf("%f", &add->array.am )); //loop untill other than float
getchar();
printf("Enter unit: ");
fgets((add->array.u), UL, stdin);
add->array.u[strlen(add->array.u)-1] = '\0';
(*items)++;
}
}
void printCities(struct array *all, int items)
{
printf("\n\n%-20s %-15s %-9s | %-6s\n", "Name", "amount", "unit");
printf("--------------------------------------------------------\n");
for(int i = 0; i < items; i++)
printf("%-20s %-15.1f %-9.4s \n", all[i].array.n, all[i].array.am, all[i].array.u);
}
This is my loop beside that i am only showing a part of the code. It now just continues to give enter amount and letting me register it in the struct. I want to restrict the user to only entering positive numbers and no character at all. And if he types a character it should rerun the loop even if it is 123Av123 it should run the loop and only register the correct number
Edit: now showing the whole code//loop untill other than float is what i want help with
int check=scanf("%f", &add->array.am )
if(check!=1||add->array.am<0){
printf("Incorrect input");
return 1;
}
I think that will do it.
Edit: you wanted it to rerun after so use continue; instead of return;
#include<stdio.h>
int main(void)
{
int sum(), sub(), mul(), div();
char ans;
printf("\ta) Add\n");
printf("\tb) Sub\n");
printf("\tc) Multiply\n");
printf("\td) Divition\n");
scanf_s("%c",&ans);
printf("\nYour answer is %c",ans);
if((ans == 'A')||(ans == 'a'))
printf("The sum of Two number is %d\n",sum());
else if((ans == 'B')||(ans == 'b'))
printf("The subraction of Two number is %d\n",sub());
else if((ans == 'C')||(ans == 'c'))
printf("The product of two number is %d\n",mul());
else if((ans == 'D')||(ans == 'd'))
printf("The divition of two number is %d\n",div());
else
printf("Enter the valid option\n");
}
int sum()
{
int x,y;
printf(" Addition\n");
printf("Enter the first number = ");
scanf_s("%d",&x);
printf("Enter the second number = ");
scanf_s("%d",&y);
return x+y;
}
int sub()
{
int x,y;
printf(" Subraction\n");
printf("Enter the first number = ");
scanf_s("%d",&x);
printf("Enter the second number = ");
scanf_s("%d",&y);
return x-y;
}
int mul()
{
int x,y;
printf(" Mltification\n");
printf("Enter the first number = ");
scanf_s("%d",&x);
printf("Enter the second number = ");
scanf_s("%d",&y);
return x*y;
}
int div()
{
int x,y;
printf(" Divition\n");
printf("Enter the first number = ");
scanf_s("%d",&x);
printf("ENter the second number = ");
scanf_s("%d",&y);
return x/y;
}
scanf_s("%c",&ans);
the function scanf does not recognize my input
whats wrong in the code
when i use
ans=getchar();
is working perfect but.. the scanf does not recognize what i input
can any one explain the problem in the code iam using visual studio 2010
To scan a single char you have to put a blank space before %c:
scanf(" %c", &char);
The blank space is needed to consume any \n char in the input buffer. You must put the blank space just for char type.
This is a program I am making for a class. It is supposed to read a letter from a file, and then in the game the user tries do guess the letter. with every wrong attempt the program tells you if the actual letter comes before or after your guess in the alphabet.
For some reason when I run it, the loop skips the first attempt in the getLetter function and does not let you input the letter. Why is this?
#include <stdio.h>
#include <ctype.h>
#define MaxGuesses 5
void instructions();
int playGuess (char solution);
char getLetter ();
int compareLetters (char guess, char solution);
int main()
{
int numGames;
int i;
char solution;
char guess;
int result;
FILE *inFile;
inFile=fopen("inputLet.txt","r");
instructions();
scanf("%d", &numGames);
for(i=1; i<=numGames; i++)
{
printf ("\nThis is game %d\n", i);
fscanf(inFile, " %c", &solution);
result = playGuess(solution);
if (result == 1)
printf("You've WON!\n");
else
printf("You've LOST :(\n");
}
//close file
fclose(inFile);
return 0;
}
void instructions ()
{
printf ("This game consists of guessing letters.\nThe user will have up to 5 chances of guessing correctly,\nupon every failed attempt,\na hint will be provided regarding alphabetical position.\n\nEnter the number of games you wish to play (max 4): ");
}
char getLetter()
{
char userGuess;
printf("\nPlease enter your guess: ");
scanf("%c", &userGuess);
userGuess = tolower(userGuess);
return userGuess;
}
int compareLetters(char guess, char solution)
{
if (guess == solution)
return 1;
else if (guess < solution)
{
printf("\nThe letter that you are trying to guess comes before %c", guess);
return 0;
}
else if (guess > solution)
{
printf("\nThe letter that you are trying to guess comes after %c", guess);
return 0;
}
}
int playGuess (char solution)
{
int numGuesses = 0;
int winOrLose = 0;
char guess;
while(numGuesses < MaxGuesses && winOrLose == 0)
{
guess = getLetter();
winOrLose = compareLetters(guess, solution);
numGuesses++;
}
return winOrLose;
}
It may be consuming a character left in the input buffer (possibly a newline or other whitespace character). You could try changing the format string from "%c" to " %c" as you've done elsewhere, which will skip all the whitespace characters in the buffer before trying to read a character.