Having trouble using string - c

Q) Help out our canteen and develop a program for cash
counter where user selects items out of 5 options with price .
The program keeps on asking until user hit 'q'. After check
out calculate total amount and show user the items purchased.
#include <stdio.h>
int main()
{
char menu[5][15]={"Pizza","Burger","Ice Cream","Pasta","Cold Drink"};
int price[5]={1000,500,300,100,50};
int i,amount=0,total=0,item=0;
printf("\t\t=========ALI FAST FOOD========");
printf("\n\t\tPlease select any option from below\n");
for (i=0;i<5;i++)
{
printf("\nAvailable items are %s press %d",menu[i],item+1);
printf("\tPrice is %d",price[i]);
printf("\n");
item++;
}
int choice;
int start;
printf("Enter number to start buying food");
do {
scanf("\n%d ",&choice);
if (choice==1)
{
static int count=0;
amount = amount+price[0];
printf("\nYou bought %d %s",count+1,menu[0]);
count++;
}
else if (choice==2)
{
static int count=0;
amount = amount+price[1];
printf("\nYou bought %d %s",count+1,menu[1]);
count++;
}
else if (choice==3)
{
static int count=0;
amount = amount+price[2];
printf("\nYou bought %d %s",count+1,menu[2]);
count++;
}
else if (choice==4)
{
static int count=0;
amount = amount+price[3];
printf("\nYou bought %d %s",count+1,menu[3]);
count++;
}
else if (choice==5)
{
int count=0;
amount = amount+price[4];
printf("\nYou bought %d %s",count+1,menu[4]);
count++;
}
else if (choice==0 || choice>=7)
{
printf("\nEnter correct option please\n");
}
}
while (choice!=6);
total = total + amount;
printf("\nTotal amount to be pay is %d",total);
printf("\nThank you for visiting our canteen have a nice day !");
}
In this i need to end the program when user enters "q" instead of "6" . i am unable to do so, please help me fix this issue.

As suggested by "Cid" try handling the input as characters instead of
integers.
Also, as suggested by "JohnBode" use a blank space before "%c" and
not before and after "%c"(i suspect that you tried using a blank
space after the "%c" as well). Let me know if I am mistaken.
Putting it together, you code should look like this....
#include <stdio.h>
int main()
{
char menu[5][15]={"Pizza","Burger","Ice Cream","Pasta","Cold Drink"};
int price[5]={1000,500,300,100,50};
int i,amount=0,total=0,item=0;
printf("\t\t=========ALI FAST FOOD========");
printf("\n\t\tPlease select any option from below\n");
for (i=0;i<5;i++)
{
printf("\nAvailable items are %s press %d",menu[i],item+1);
printf("\tPrice is %d",price[i]);
printf("\n");
item++;
}
char choice;
int start;
printf("Enter number to start buying food\n");
do {
scanf(" %c",&choice);
if (choice=='1')
{
static int count=0;
amount = amount+price[0];
printf("\nYou bought %d %s\n",count+1,menu[0]);
count++;
}
else if (choice=='2')
{
static int count=0;
amount = amount+price[1];
printf("\nYou bought %d %s\n",count+1,menu[1]);
count++;
}
else if (choice=='3')
{
static int count=0;
amount = amount+price[2];
printf("\nYou bought %d %s\n",count+1,menu[2]);
count++;
}
else if (choice=='4')
{
static int count=0;
amount = amount+price[3];
printf("\nYou bought %d %s\n",count+1,menu[3]);
count++;
}
else if (choice=='5')
{
int count=0;
amount = amount+price[4];
printf("\nYou bought %d %s\n",count+1,menu[4]);
count++;
}
//checking for lower and upper case "q"
else if (choice=='0' || choice >= '6' && (choice != 'q' && choice != 'Q'))
{
printf("\nEnter correct option please\n");
}
} while (choice!='q' && choice!='Q');//checking for lower and upper case "q"
total = total + amount;
printf("\nTotal amount to be pay is %d\n",total);
printf("\nThank you for visiting our canteen have a nice day !\n");
}

Related

Is my do while loop not working due to this function?

Im making a program where it asks the user to guess a number 1-100 that the computer is thinking about.
In the end of the program, when the user has guessed the correct number, im trying to get the program to ask if user wants to play again (restart the program).
To solve this, i tried using a do while loop & char repeat;. The loop is stretching from almost the beginning of the program, until the end, althought without success. Does anyone know what im doing wrong? Is it because of the function talfunktion, that the loop won't pass?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int talfunktion (int tal, int guess, int tries, char repeat);
int main () {
do {
srand(time(NULL));
int tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char repeat;
printf("Psst, the right number is: %d \n", tal); // remove later, not relevant to uppg.
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
guess = talfunktion(tal, guess, tries, repeat);
getchar();
getchar();
return 0;
}
int talfunktion(int tal, int guess, int tries, char repeat) {
do {
if (guess < tal) {
tries++;
printf("\nYour guess is too low, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
else if (guess > tal) {
tries++;
printf("\nYour guess is too high, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
} while (guess > tal || guess < tal);
if (guess == tal) {
printf("\nCongratulations, that is correct!");
tries++;
printf("\nYou made %d attempt(s)", tries);
printf("\nPlay Again? (y/n)");
scanf("%c", &repeat);
}
} while (repeat == 'y' || repeat == 'Y');
}
This is one possible solution
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void talfunktion(int tal, int guess, int* tries)
{
if (guess < tal)
{
(*tries)++;
printf("\nYour guess is too low, try again!");
}
else if (guess > tal)
{
(*tries)++;
printf("\nYour guess is too high, try again!");
}
else if (guess == tal)
{
(*tries)++;
printf("\nCongratulations, that is correct!");
printf("\nYou made %d attempt(s)", *tries);
}
}
int main (void)
{
int tal; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char playAgain;
do {
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
printf("\nIm thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
talfunktion(tal, guess, &tries);
printf("\nPsst, the right number is: %d", tal); // remove later, not relevant to uppg.
getchar(); //to halt the code for taking the input
if(guess == tal)
{
tries = 0;
printf("\nPlay Again? (y/n)\n");
scanf("%c", &playAgain);
}
} while (playAgain != 'n');
return 0;
}
There are several things mentioned in the comments that describe problems,
Things you should look at:
Do not define a function inside another function
be careful where you place return statements
when using character testing, use char type for variable
consider simplifying your logical comparisons. (eg guess > tal || guess < tal is the same as guess != tal )
make sure automatic variables are placed such that they are visible where used.
Place space in format specifier: " %c" for scanf() to consume newline character. (instead of excessive use of getchar())
Here is a simplified version of your code, with modified main and talfunktion functions...
char talfunktion(int tal);
int main (void) {
int tal=0;//remove from inside {...} to make it visible to rest of function
char repeat = 'n';
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
do {
repeat = talfunktion(tal);
}while((tolower(repeat) == 'y'));
return 0;
}
char talfunktion(int tal)//do all relevant work in function and return
{ //only what is necessary
int guess = 0;
char repeat = 'n';
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter a number from 1 to 100: ");
scanf("%d", &guess);
if((guess < 1) || (guess > 100))
{
printf("Entered out of bounds guess...\n");
}
else if (guess != tal)
{
if(guess < tal) printf("guess too small\n");
else printf("guess too large\n");
printf("Try again? <'n' or 'y'>\n");
scanf(" %c", &repeat);//space in format specifier to consume newline character
if(tolower(repeat) != 'y') return 'n';//tolower() allows both upper and lower case
}
else
{
printf("Congratulations: You guessed right.\n");
printf("Play again? <'n' or 'y'>\n");
scanf(" %c", &repeat);
}
return repeat;
}

I cant seem to understand how to restrict my scanf to only numbers of float

#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;

How to store the users input into an array?

I know from my code it's a bit of a mess as I'm a beginner to programming. I just wanted to see if someone could just quickly help me out by letting me know how to get the users input stored into an array and do what my code already does. So, I want the user to input the amount of tickets and then that gets stored in an array then printed like my code already does. Just want to try and cut down my code as it is very messy and need to store it in an array I've been told but I'm stumped at the moment.
#include <stdio.h>
#include<conio.h>
#include<stdbool.h>
#define MAX 10
void showPrices();
void showRoutes();
void orderTickets();
void main()
{
int userChoice;
while(1)
{
// Looping the menu for the user
printf("\n\n**** MENU ****");
printf("\n*NOTE* MAX TICKETS PER CUSTOMER = 10");
printf("\n1. Show Prices\n2. Show Routes\n3. Order Tickets\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d", &userChoice);
//gets to chose between the different options
switch(userChoice)
{
case 1: showPrices();
break;
case 2: showRoutes();
break;
case 3: orderTickets();
break;
case 4: exit(0);
default: printf("\nInvalid, try again!!!");
}
}
}
void showPrices()
{
//for the switch statement, this is what I want to be displayed when they pick this option
printf("\n\n---- Prices - ALL DAY ----");
printf("\n1. Child = £3\n2. Teenager = £5\n3. Standard = £10\n4. Student = £7\n5. Senior = £6");
}
void showRoutes()
{
//for the switch statement, this is what I want to be displayed when they pick this option
printf("\n\n---- Routes - ALL DAY ----");
printf("\n---- Leaving from Nottingham Station ----");
printf("\nDestinations:\nDerby\nLeicester\nSheffield\nBirmingham");
}
void orderTickets()
{
int ticketArray[tickets];
int age;
int userInput = 0;
int tickets;
int ticketSum = 0;
int ticketNumber = 1;
int sum;
int userDesti;
//Main function where the user oders the tickets!
printf("\nWhere do you want to go?");
printf("\n1. Derby\n2. Leicester\n3. Sheffield\n4. Birmingham");
scanf("%d", &userDesti);
//asks the user how many tickets they want
printf ("\nHow many tickets do you need?: ");
scanf ("%d", &tickets);
//loop to keep asking the user to input the information they need to enter for each ticket until it reaches 0
while (tickets > 0)
{
/*only does this if they enter 10 or less and more than 0
if (tickets <= 10 && tickets > 0)
{
printf("\nHow old are you?: ");
scanf("%d", &age);
if(age < 10)
{
printf("\nChild Ticket = £3\n");
ticketSum = ticketSum + 3;
}
else if (age < 16)
{
printf ("\nTeenager Ticket = £5\n");
ticketSum = ticketSum + 5;
}
else if (age >= 16 && age < 60)
{
printf("\nStandard Ticket = £10\n");
ticketSum = ticketSum + 10;
}
else
{
printf("\nSenior Ticket = £6\n");
ticketSum = ticketSum + 6;
}
}
//if they enter an invalid number
else
{
printf("Error, invalid number of tickets!!\n");
break;
}*/
// this allows the student discount to be deducted from the final price
printf("\nAre you a student? Enter 1 for yes or 2 for no: ");
scanf("%i", &userInput);
if(userInput == 1)
{
printf ("\nYou are eligible for the student discount = £3 deducted\n");
//sum to deduct the discount
ticketSum = ticketSum - 3;
}
//if they aren't a student then they will get this message
else if (userInput == 2)
{
printf ("\nYou are not eligible for the student discount, sorry!\n");
}
// gives the user their number for that ticket
printf("\n------------------");
printf("\nTicket Number: %d ", ticketNumber);
printf("\n------------------\n");
ticketNumber++;
// lets the user know how much each ticket adds onto the previous
printf("\n-----------------------");
printf("\nThe summary so far: %d ", ticketSum);
printf("\n-----------------------\n");
// gets out of the main loop when the tickets are less than or equal to 0
if (tickets <= 0 )
{
break;
}
//takes away the value of tickets each time so if they want 2 tickets then it takes away 1 so then it equals 1 left umtil it reaches 0
tickets--;
}
//the receipt of all the tickets added together.
printf("\n-----------------------------------");
printf("\n-----------------------------------");
printf("\nThe receipt for your order: £%d", ticketSum);
printf("\n-----------------------------------");
printf("\n-----------------------------------");
}

Split a phone number into three groups

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]);
}

c programming language : the app wont stop after typing x

i made this program and its working just how i want but it should stop when i type x but it doesn't
can any one tell me why?
and if there is any shortcut or smaller way to type this code?
thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int meat[6];
int i;
int total =0;
int avg;
char what[20];
char end;
int days = 0;
char food[20];
char drink[20];
printf("what thing do u want to calculate the average of?(food/drink)\n");
scanf(" %s", &what);
if(strcmp(what, "food")==0)
{
printf("what sort of food did u ate ?\n");
scanf(" %s", food);
}
if(strcmp(what, "drink")==0)
{
printf("what sort of drink did u drank ?\n");
scanf(" %s", drink);
}
for(i=0; i<6; i++)
{
days++;
if(strcmp(what, "food")==0)
{
printf("how many %s did u ate in day %d\n", food, i+1);
}
else if(strcmp(what, "drink")==0)
{
printf("how many liters of %s did u drank in day %d\n", drink, i+1);
}
scanf(" %d", &meat[i]);
total += meat[i];
printf("if u want to continue type y\n");
printf("type x if u want to finish\n");
scanf(" %c", &end);
if((end = 'y')&&(i<5))
{
continue;
}
else if(end = 'x' && strcmp(what, "drink")==0)
{
avg = total / days;
printf("\nyour average amount of liters of %s you had %d\t the total is %d\n", drink, avg, total);
}
else if(end = 'x' && strcmp(what, "food")==0)
{
avg = total / days;
printf("\nyour average amount of %s you had %d\t the total is %d\n", food, avg, total);
}
break;
}
if(strcmp(what, food)==0)
{
printf("\nyour average amount of %s you had is %d\t the total is %d\n", food, avg, total);
}
else if(strcmp(what, drink)==0)
{
printf("\nyour average amount of liters of %s you had is %d\t the total is %d\n", drink, avg, total);
}
return 0;
}
else if(end = 'x' ...
should be:
else if(end == 'x' ...
You use == to test equality in if statements. You've got this in a couple places in your code, which is inadvertently performing an assignment, not what you want to achieve by comparing if user input is equal to a particular character.
Replace the = with == here:
else if(end = 'x' && strcmp(what, "drink")==0)
here:
else if(end = 'x' && strcmp(what, "food")==0)
and here:
if((end = 'y')&&(i<5))

Resources