C - 2 or more input validation inside while loop - c

I have a program in which it will ask for the user to record the student's name and grade. One of the functions I used is for the user to edit the record of the student. The code works but now what I'm scratching my head is how to implement a validation of input by the user. I tried searching but I can't find the exact answer I need.
I already implemented the first validation and it works, but now what I want for the second validation is to go back and ask again instead of breaking the loop.
Here's my code:
void update(struct data list[80], int num)
{
int count, tmp, rolltmp, option;
system("cls");
while(tmp < 1 || tmp > num)
{
printf("How many student records do you want to edit?: ");
scanf("%d",&tmp);
if(tmp >=1 && tmp <=num)
{
printf("\nEditing the Student Record: ");
for(count=0;count<tmp;count++)
{
printf("\nEnter Roll Number for Student #%d: ",count+1);
scanf("%d",&rolltmp);
if(rolltmp >=1 && rolltmp <= num)
{
fflush(stdin);
printf("\n[CHOICES]");
printf("\n[1] - Edit the Name\n[2] - Edit the Grade\n[3] - Edit Both Name and Grade");
printf("\nEnter Choice: ");
scanf("%d",&option);
switch(option)
{
case 1:
fflush(stdin);
printf("\nEnter New Name: ");
gets(list[rolltmp-1].name);
break;
case 2:
printf("\nEnter New Grade: ");
scanf("%d",&list[rolltmp-1].grades);
break;
case 3:
fflush(stdin);
printf("\nEnter New Name: ");
gets(list[rolltmp-1].name);
fflush(stdin);
printf("\nEnter New Grade: ");
scanf("%d",&list[rolltmp-1].grades);
break;
}
}
else
{
printf("\nNot Valid. Please enter from 1 to %d\n",num);
printf("Press any key to enter again...\n\n");
getch();
break;
}
}
}
else
{
printf("Not Valid. Please enter from 1 to %d",num);
getch();
break;
}
}
}

Related

Tried to make C Program Menu Option, but the code is running on loop

int main()
{
int choice;
printf("Enter the size of array: ");
scanf("%d", &size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do
{
printf("\n******** Main Menu ********\n");
printf("1. Display\n");
printf("2. Sort\n");
printf("3. Reverse\n");
printf("4. Search\n");
printf("5. Exit\n");
printf("Enter Your Choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
display(size);
break;
case 2:
sort(size);
break;
case 3:
reverse(size);
break;
case 4:
printf("Enter the value to search: ");
scanf("%d", &val);
search(val, size);
break;
case 5:
break;
default:
printf("Invalid Choice\n");
break;
}
} while (choice != 5);
return 0;
}
I was expecting it to show 4 choices and I do the user input, but its running on loop with input 'Invalid Choice'. This is just the part of long code.
Your program doesn't compile due to missing function and variable definitions, and it's also missing includes.
When you ask scanf("%d", &choice) to read an integer but pass something else, like 'a', it will fail, not set choice and it will also leave the unexpected input in the buffer. Below I handle the failure by giving setting choice = 0 which is invalid input, and flush the unexpected data from the input buffer. As we only have 5 valid choices use a char choice.
#include <stdio.h>
#include <stdlib.h>
void display(size_t size) {
printf("display\n");
}
void reverse(size_t size) {
printf("reverse\n");
}
void search(int val, size_t size) {
printf("search\n");
}
void sort(size_t size) {
printf("sort\n");
}
void flush() {
for(;;) {
switch(getchar()) {
case EOF:
case '\n':
return;
}
}
}
int main() {
printf("Enter the size of array: ");
size_t size;
if(scanf("%zu", &size) != 1 || !size) {
printf("invalid size\n");
return 1;
}
int arr[size];
for (size_t i = 0; i < size; i++)
if(scanf("%d", &arr[i]) != 1) {
printf("invalid input\n");
return 1;
}
char choice;
do {
printf("\n******** Main Menu ********\n");
printf("1. Display\n");
printf("2. Sort\n");
printf("3. Reverse\n");
printf("4. Search\n");
printf("5. Exit\n");
printf("Enter Your Choice: ");
choice = 0;
scanf("%hhd", &choice);
switch (choice) {
case 1:
display(size);
break;
case 2:
sort(size);
break;
case 3:
reverse(size);
break;
case 4: {
printf("Enter the value to search: ");
int val;
if(scanf("%d", &val) != 1) {
printf("invalid val\n");
return 1;
}
search(val, size);
break;
}
case 5:
break;
default:
printf("Invalid Choice\n");
break;
}
flush();
} while (choice != 5);
return 0;
}
sample session:
Enter the size of array: 3
1
2
3
******** Main Menu ********
1. Display
2. Sort
3. Reverse
4. Search
5. Exit
Enter Your Choice: 1
display
******** Main Menu ********
1. Display
2. Sort
3. Reverse
4. Search
5. Exit
Enter Your Choice: x
Invalid Choice
******** Main Menu ********
1. Display
2. Sort
3. Reverse
4. Search
5. Exit
Enter Your Choice: 5

How to reject user input if it is not valid and make him input again

I'm creating a program that asks for input and then based on the input rejects it or accepts it. This is the code:
while(1){
printf("Enter name: ");
scanf("%s", &name);
if(name[0] == '\0'){
printf("Input Cannot be empty\nExample: bobshmurda\n");
} else {
break;
}
}
printf("Enter age: ");
scanf("%d", &age);
while(!age>= 15){
printf("Age\n");
}
while(1){
printf("Enter MMN: ");
scanf("%d", &mmn);
if (!cvv >= 3){
printf("\nInvalid MMN... Try again\n");
} else {
break;
}
}
while(1){
printf("DOB: ");
scanf("%d", &dob);
if (!exp == 4){
printf("Invalid DOB detected... Format: 0123\n");
} else {
break;
}
}
What i basically want to do is i want to for example IF age is greater than 100 or less than 0 do this, etc. Same with strings how would i do that?
A do-while loop is probably the simplest method:
int is_valid = 0;
do {
// Get user input here
is_valid = validate_input(...);
} while (! is_valid);
// Continue with processing...

I can't print, is the data not inserted or is there something wrong in the loop?

I need to make some storage record, I need to be able to insert, see the data, and search according to an id (I haven't reached the search part yet). My problem is either the data not recorded, or it couldn't be printed both of them due to indexing problem imo. what do I need to do?
struct item{
char *name;
int qty;
}item [10];
int main ()
{
int i=0,n,menu;
printf("Goody Storage\n");
printf("=============\n");
printf("Input Storage[1..10]: ");
scanf("%d",&n);
for(;;i++){
if(n<=10){
printf("\nGoody Storage\n");
printf("=============\n");
printf("\n1. Add Items\n");
printf("2. See Items\n");
printf("3. Search Items\n");
printf("4. Exit\n");
printf("Choose Menu[1..4]: ");
scanf("%d",&menu);
switch(menu){
case 1 :
printf("Input name of item %d: ", i+1);
scanf("%s",&item[i].name);
printf("Input qty of item %d: ", i+1);
scanf("%d",&item[i].qty);
continue;
case 2 :
printf("\nNo.\tName\t\t\tQuantity\n");
printf("========================================\n");
printf("%d\t%s\t\t\t%d\n", i, item[i].name, item[i].qty);
continue;
/*case 3 :
printf("\nInvalid Choice");
continue;*/
case 4 :
return 0;
default :
printf("\nInvalid Choice");
}
} else break;
}
}

In checkout function g_tot calculation brings garbage value

In this code at checkout function g_tot calculation brings garbage value. I think its because I'm calculating two variables from another two functions, but I don't know how to fix it. There's another error in restaurant function in if condition if I enter value more than 8 it'll bring garbage value to tot. But the most important one is
#include<stdio.h>
#include<conio.h>
// Global variables
int room,answr,days=0;
char name[20],choose;
int i=0,tot=0,p_tot=0,g_tot=0,z=0;
int p_price[2][5]={4000,10000,20000};
void screenheader()
{
printf("\n ::::::::::::::::::::::::::::::::::::::");
printf("\n :: ::");
printf("\n :: ############################ ::");
printf("\n :: # # ::");
printf("\n :: # WELCOME # ::");
printf("\n :: # TO # ::");
printf("\n :: # SURF HOTEL # ::");
printf("\n :: # # ::");
printf("\n :: ############################ ::");
printf("\n :: ::");
printf("\n ::::::::::::::::::::::::::::::::::::::");
}
void check_in()
{
int contact_No[20],NIC[10];
char first_name[10],last_name[10],Country[10];
system("cls");
screenheader();
printf("\n1. Packages");
printf("\n2. Room Allocation");
printf("\n3. Back\n\n");
scanf(" %d",&answr);
switch(answr)
{
case 1:{
system("cls");
printf("\n\n\nPer 2 Persons");
printf("\n\t\tPackage Name >>>> Couple");
printf("\n\t\tRs.4000/= per day");
printf("\n\t\tBed >>>> 1");
printf("\n\t\t *Tv Available");
printf("\n\n\n\n\t\t\nPer 4 Persons\n\t\tPackage Name >>>>
Family");
printf("\n\t\tRs.10,000/= per day");
printf("\n\t\tBed >>>> 2");
printf("\n\t\t*Tv Available \n\t\t*A/C \n\t\t*WIFI");
printf("\n\n\n\nPer 8 Persons\n\t\tPackage Name >>>> Deluxe");
printf("\n\t\tRs.20,000/= per day");
printf("\n\t\tBed >>>> 3 Large ");
printf("\n\t\t *Tv Available \n\t\t*A/C \n\t\t*WIFI\n\t\t*Local
Travel Guide\n\t\t*Balcony with a view\n\t\t*Writing desk");
printf("\n\n*Press 1 to go back");
getch();
check_in();
break;
}
case 2:{
printf("What package do you want?");
scanf(" %d",&i);
p_tot=p_tot+p_price[i-1];
if(i == 1)
{
printf("You have selected Couple package");
}
else if (i == 2)
{
printf("You have selected Family Package ");
}
else if (i == 3)
{
printf("You have selected Deluxe package");
}
else
{
printf("\n\nWrong input, please refer to packages and try
again.\nPress Enter to select another package");
getch();
check_in();
}
printf("\nEnter First Name:\n");
scanf(" %s",&first_name);
printf("Last Name:\n");
scanf(" %s",&last_name);
printf("How many days do you want to stay?");
scanf(" %d",&days);
printf("Enter your Country:");
scanf(" %s",&Country);
printf("Enter your NIC No:");
scanf(" %d",&NIC);
printf("Enter your Contact No:");
scanf(" %d",&contact_No);
printf("Hello %s %s you have booked a Room for
%d",&first_name,&last_name,days);
getch();
system("cls");
int main();
}
case 3: main();
}
}
void restaurant()
{
int fc[6];
char ans;
char food[8][30]={"Bread","Noodles","Salad","Popcorn","Chocolate ice
cream","Vanilla ice cream","Cold Coffee","Milk Shake"};
int price[8]={180,120,65,55,70,70,110,200};
printf("Press Enter To Continue To The Restaurant ");
getchar();
system("cls");
printf("\n\n\n\n\n\t *********");
printf("\n\t MENU CARD");
printf("\n\t *********\n\n\n");
printf("\n Food Code\t\tprice\t\t Food Name\n");
for(i=0;i<8;i++)
{
printf("\n\t\t%d",i+1);
printf("\t\tRs. %d",price[i]);
printf("\t\t%s",food[i]);
}
printf("\n\n\n\t *PRESS 0 TO GO TO THE MAIN MENU\n\t *PRESS 1 TO ORDER FOOD
: ");
scanf(" %d",&answr);
switch(answr)
{
case 0:
{
main();
break;
}
case 1:do
{
printf("\n\nENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf("%d", &z);
if (z < 1 || z > 8)
{
printf("Invalid food code\n");
}
tot=tot+price[z-1];
printf("total so far is Rs.%d\n",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c", &ans);
} while(ans=='y'|| ans=='Y');
printf("\n\nYour bill is Rs.%d",tot);
printf("\nYour bill will be added to the total bill at checkout");
printf("\n\nPress Enter to go back to main menu");
getch();
system("cls");
main();
}
}
void check_out()
{
system("cls");
screenheader();
printf("\n\nAre you sure you want checkout (Y/N)");
scanf(" %c",&choose);
if(choose=='n' || choose=='N')
{
main();
}
else if(choose== 'Y' || choose=='y')
{
system("cls");
screenheader();
g_tot=p_tot+tot;
printf("Total");
printf("%d",g_tot);
}
}
int main()
{
screenheader();
printf("\n\n\nPress Enter To Continue");
getchar();
system("cls");
screenheader();
printf("\n\n\n\n\t\t ************* \n");
printf("\t\t * MAIN MENU * \n");
printf("\t\t ************* \n\n\n");
printf("\t\t\t01. Check In \n");
printf("\t\t\t02.Restaurant\n");
printf("\t\t\t03.Checkout \n");
printf("\n\t\t\t04.Exit");
scanf(" %d",&answr);
switch(answr)
{
case 1:{
check_in();
break; }
case 2:{
restaurant();
break; }
case 3: {
check_out();
}
}
return 0;
}
if condition if I enter value more than 8 it'll bring garbage value to tot.
This is as expected. When z > 8, code attempts to access outside price[] range. Result: undefined behavior (UB). The prior if (z < 1 || z > 8) did not steer code away from price[z - 1]. Rest of code including g_tot = p_tot + tot; is now questionable.
int price[8] = {180, 120, 65, 55, 70, 70, 110, 200};
...
if (z < 1 || z > 8) {
printf("Invalid food code\n");
}
tot = tot + price[z - 1]; // UB here
...
g_tot = p_tot + tot;
Do not access price[z - 1] unless z in the range [1...8].
Other problems exist: Best to enable all compilers warnings and seem them (12+) yourself.

scanning an array and assign it into other place in C

help me. I've been assign to make an application for some test result. but why can't I print out what user have inputted at case 2. I've tried other approach but it's not working. this is the closest I could get there. Any help would be appreciated. super thanks +_+
this is my code :
int main(){
int option;
char namamurid[30][15];
int i=0,j=0;
int listening[15];
int reading[15];
int essay[15];
int score[15];
do{ printf("\"Smart English\" Course Center\n********************************\n");
printf("1.Add new data\n2.View data\n3.View summary\n4.Exit\n\n");
printf("your option[1..4]: ");
scanf("%d",&option);
fflush(stdin);
switch(option){
case 1:
do{
printf("Input student's name[1..25 char]: ");
scanf("%[^\n]s",namamurid[i]);
fflush(stdin);
}while(strlen(namamurid[i])<1 || strlen(namamurid[i])>25);
do{
printf("Correct answer for listening section[0..20]: ");
scanf("%d",&listening[i]);
fflush(stdin);
}while(listening[i]<0 || listening[i]>20);
do{
printf("Correct answer for reading section[0..30]: ");
scanf("%d",&reading[i]);
fflush(stdin);
}while(reading[i]<0 || reading[i]>30);
do{
printf("Correct answer for essay section[0..25]: ");
scanf("%d",&essay[i]);
fflush(stdin);
}while(essay[i]<0 || essay[i]>25);
break;
case 2:
printf("Name\t\tListening\tReading\tEssay\tScore\tGrade\n");
for(j=0;j<i;j++)
{
printf("%-1s\t\t%d\t%d\t%d\t%d\n",namamurid[j],listening[j],reading[j],essay[j],score[j]);
}
break;
}
} while(option<1 || option>4 || option !=4);
getchar();
return 0;
}
There is no change to value of variable i which is set to 0 during initialization.Hence it will never enter the for loop in case 2.

Resources