how to repeat a menu after dealing with wrong input - c

So the assignemt is to print a menu with options, and if the user puts in an invalid choice (not 1,2,3,4,5 ,6), it prints an error and asking the user to choose again.
if the user puts in a wrong input 5 times total, the programm will exit.
int main() {
printf("Welcome, please choose one of the options below: \n ");
printf( "1.Exit \n ");
printf( "2.Print menu again \n ");
printf( "3. ");
printf( "4.. ");
printf( "5. ");
printf( "6. ");
printf("Enter your choice: ");
scanf("%d" , &choice);
if( (choice > 6) || (choice < 1) ) {
do {
count++;
printf(" Wrong input, please try again (Enter 2 for re-printing the menu). \n " );
printf("Enter your choice: ");
scanf("%d", &choice);
if(choice==2){
do {
printf("Welcome, please choose one of the options below: \n "); //prints of the screen the following in a loop
printf("1.Exit \n ");
printf("2.Print menu again \n ");
printf("3. ");
printf("4. ");
printf("5. ");
printf("6.");
printf("Enter your choice: ");
scanf("%d", &choice);
} while (choice==2);
}
} while (count < 4) ;
printf("%s" , "You have made 5 menu errors.Bye Bye!!! \n ");
}
while(1) {
.
}
*the while(1)is for the entire code, puts the entire code for re-use
** i didnt use switch-case, cuz it's forbidden to use it
Now, the problem is, that if i put a wrong input first, let's say for example, '7' (which isn't a choice from the menu), it will print "wrong input, please try again". So far so good.
But then,if I press 2 for re-printing the menu, and then I press any number, even if it's a valid choice, it's printing "wrong input".
also, if I press '2' for re-printing the menu, and then press 1, it will require to press 1 twice in order to exit the programm, instead of just pressing once.

The above answers look correct but you can go with the following code as its working and easy to understand for anyone!
#include <stdio.h>
void printMenu()
{
printf("Welcome, please choose one of the options below: \n ");
printf( "1.Exit \n ");
printf( "2.Print menu again \n ");
printf( "3. ");
printf( "4.. ");
printf( "5. ");
printf( "6. ");
}
int main()
{
int choiceValid=0, count=0, choice;
printMenu();
while(choiceValid==0 && count<=5)
{
printf("Enter your choice: ");
scanf("%d" , &choice);
if(choice==2)
{
printMenu();
continue;
}
if( choice<=6 && choice>=1 )
choiceValid=1;
else
{
count++;
printf("\nWrong input, please try again (Enter 2 for re-printing the menu). \n " );
}
}
return 0;
}

Replace your if(choice==2) with if((choice==2) || (choice > 6) || (choice < 1) )
Replace while (choice==2);with while (((choice==2) || (choice > 6) || (choice < 1) ) && (count < 4))
Put the following block inside the same while loop.
if(2 == choice) count = 0;
else if (choice > 6) || (choice < 1) count ++;

Related

How to exit program when the choice is not equal to "y"

I am trying to make a program that would print 10 integers between 10-50 in an array and when you enter an integer outside 10-50 it would ask you if you want to try again or not. But when I try to enter "n" it would still continue to ask another integer. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#define size 10
int main() {
int i,arr[size],sum=0;
char ch;
do {
for(i = 0; i < size; i++){
printf("Input a number at index %d: ", i);
scanf("%d", &arr[i]);
if(arr[i] <10 ||arr[i] > 50 ){
printf("entered number is not valid\n");
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
}
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
while (ch == 'y' || ch == 'Y');
}
In this if statement you ask whether the user wants to continue or not, but do not handle the situation where the user enters an 'n'. You must enter a comparison followed by a break to exit the loop.
if (arr[i] < 10 || arr[i] > 50){
printf("entered number is not in the range 10..50\n");
printf("Do you want to repeat the operation Y/N: ");
scanf(" %c", &ch);
// ADD THE FOLLOWING TO YOUR CODE
if (ch != 'y' && ch != 'Y')
break;
}

Some logical Error in basic registration system in C

I got an assignment to make a program for a registration system, here I have completed it half as it registers the user but when it comes to logging in, I am unable to get an output whereas I believe the program is correct! I am trying to compare two arrays one that we used for registration and the second for the login input.
int main(){
char password[20],user_nam[7];
int length=0,l1,length2=0,num_f=0,cap_f=0,sm_f=0,t=0,choice=0;
int i=0,count1=0,count2=0;
printf("\nPlease Enter your User-Name(5 alphabets): ");
gets(user_nam);
for (length2 = 0; user_nam[length2] != '\0'; ++length2);
printf("\n %d",length2);
if (length2==5){
printf("\nYour password should validate following conditions;");
printf("\n 1. 6 Characters!\n 2. Atleast 1 numeric! \n 3. Atleast 1 Capital! \n 4. Atleast 1 small letter!");
printf("\n\nPlease Enter your passowrd: ");
gets(password);
for (length = 0; password[length] != '\0'; ++length);
if (length==6){
printf("\n%d",length);
for (l1=0;l1<length;l1++){
if (password[l1]>='a' && password[l1]<='z'){
++sm_f;}
if (password[l1]>='A' && password[l1]<= 'Z'){
++cap_f;
}
if (password[l1]>='0' && password[l1]<='9'){
++num_f;
}
}
if (num_f<1){
printf("\nPlease Add atleast 1 number to the password!");
++t;}
if (cap_f<1){
printf("\nPlease add atleast 1 capital alphabet to the password!");
++t;}
if (sm_f<1){
printf("\nPlease add atleast 1 small alphabet to the password!");
++t;}
if (t==0)
printf("\nAccount Created Successfully!");
else
printf("\nTry again!");
}
else{
printf("\nPlease Enter Valid Password! Try again.");
}
}
else{
printf("\nPlease Enter valid 5 character user name!");
}
printf("\nTo Login Please Enter 1 or -1 to End: ");
scanf("%d",&choice);
char l_pass[10],l_name[7];
if (choice!=-1 && choice ==1){
printf("\nPlease Enter your user name: ");
scanf(" %c",&l_name);
printf("\n");
for (i=0;i<length2;i++){
if (l_name[i] == user_nam[i]){
(count1 = count1 + 1);
printf("%d",count1);
}
}
if (count1==5){
printf("\nPlease Enter your password: ");
gets(l_pass);
for (i=0;i<length;i++){
if (l_pass[i] == password[i])
count2+=1;
}
}
else{
printf("\nInvalid User Name!");
}
}
}
You have a problem with the line scanf(" %c",&l_name);.
Replace it with scanf("%s",l_name);

How can I modify program to set array range from 0 to 100 in program below

I need the code below to recognize if the grades entered is below 1 or greater than 100. If it is not within the parameters, I want to let the user know and allow them to enter another grade without exiting the program or losing grades they have already entered. I don't want the program to quit until the user enters q and I want to ensure all of the valid grades entered print at that time. I have tried numerous methods and am not getting the right results. I think I probably need some other else if statement, but I haven't been able to find the right one to work. Any information you can share to get me on the right track would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
You can do a while loop to verify the user input. With a while you'll be able to force the user to enter the right grade.
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
your solution is almost aligned with what you had in mind. Here is how you can do it differently.
#include <stdio.h>
int main()
{
char choice;
int arraySize = 100; //change this to any number you wish
int gradeScore = 0;
int gradeArray[arraySize];
int gCount = 0;
int showCount = 0;
while(choice != 'q')
{
//to ask for user's input every time
printf("What do you want to do? Enter\n");
printf("'a' to add grades\n");
printf("'q' to quit\n");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
//your implementation should check for user input before proceeding
if(choice != 'a')
{
//in this condition, 'q' is technically an incorrect input but your design states that 'q' is for quitting
//thus, do not alert the user here if 'q' is entered
if(choice != 'q')
{
//a condition to warn the user for incorrect input
printf("Incorrect input. Please enter only 'a' or 'q'\n");
}
}
else if(choice == 'a')
{
printf("Enter grade: \n");
scanf(" %d", &gradeScore);
//to check for user input if the grades entered are less than 1 or more than 100
if(gradeScore < 1 || gradeScore >100)
{
//print a warning message
printf("The grade you entered is invalid. Please enter a grade from 1 - 100\n");
}
//for all correct inputs, store them in an array
else
{
printf("Grade entered\n");
gradeArray[gCount] = gradeScore;
gCount++;
}
}
}
//prints grade when 'q' is entered
if(choice == 'q')
{
printf("Grades are: \n");
for(showCount = 0; showCount < gCount ; showCount++)
{
printf("%d\n", gradeArray[showCount]);
}
}
}
To sum up the important parts, be sure to check for the user grade input to be in range of 1 - 100. Store the grade in the array if it is within range and be sure to increase the array counter, otherwise it will always store it in gradeArray[0] for the subsequent grades. Hope this helps
Use a do-while loop to keep the program looping back to get another choice unless a valid choice has been entered. Use fgetc to read a single character - fewer problems. Only print grades if at least one grade has been entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection******\n Add grades(a)\n Quit(q) \n");
do
{
choice = fgetc(stdin);
if(choice == 'a' || choice == 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
else if(choice != 'q')
printf("Invalid choice - try again\n");
} while (choice != 'a' && choice != 'A' && choice != 'q');
if(choice == 'q') //if the user choice is q, then exit the loop
break;
}
if(gCount > 0)
{
printf("Grades are:\n");
for(i=0; i<gCount; i++)
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}

In C scanf skips read int value

I am trying to creating a console program with menu in c. But I have a problem about validating the option int value. When I put char value it accepts it. I am trying to catch this condition. It understands the condition but scanf is not working second time to read input. It just skips. My code below. Thanks for help!
while (true) {
printf("%s", "Choose one option: ");
while (scanf("%d", &choice) != 0) {
puts("This is not a number! Enter again:");
}
// checking input
while (choice < 1 || choice > 8){
puts("Wrong input! You can choose only 1 - 8!");
printf("%s", "Choose one option: ");
scanf("%d", &choice);
}
if (choice == 8)
break;
(*options[choice])();
}

While loop doesnt work on the first time when accessing it for the second time

Okay so I have run a function 4 times. It runs perfectly the first time but when i have to run that function again the 3 other time, i get the "* INVALID ENTRY * : " printf that i made when the user doesnt input a 'y' or 'Y' or 'n' or 'N'
Also, I am trying to make it so that whenever a user enters "Yes or No" it will prompt the "error message" but currently the way i wrote my program it takes only the first Character from the user" Ex: Inputs "Yes" the program will take only "Y" which makes the program think the user entered 'Y' which skips the error stage.
This is what is in my main
printf("Please enter 'Y' > ");
printf(" Result: %d\n", yes() );
printf("Please enter 'y' > ");
printf(" Result: %d\n", yes());
printf("Please enter 'N' > ");
printf(" Result: %d\n", yes());
printf("Please enter 'yes', then 'no', then 'n' > ");
printf(" Result: %d\n", yes());
And this is my part im trying to access.
int yes(void) {
char singleLetter;
int theResults = 0;
scanf("%c", &singleLetter);
while ((singleLetter != 'y') && (singleLetter != 'Y') && (singleLetter != 'n') && (singleLetter != 'N')) {
clearKeyboard();
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
scanf("%c", &singleLetter);
}
if ((singleLetter == 'y') || (singleLetter == 'Y')) {
theResults = theResults++;
}
if ((singleLetter == 'n') || (singleLetter == 'N')) {
theResults = 0;
}
//printf("%c",singleLetter);
return theResults;
}
The results are:
Please enter 'Y' > Y
Result: 1
Please enter 'y' > y
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: y
Result: 1
Please enter 'N' > N
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: N
Result: 0
Please enter 'yes', then 'no', then 'n' > yes
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: no
Result: 0
EDIT::
I fixed the above code so it works fine
However when I call yes() from a different function i get this error:
This is the code im trying to call from:
void getName(struct Name *contactName) {
printf("Please enter the contact's first name: ");
scanf("%s", (*contactName).firstName);
printf("Do you want to enter a middle intial(s)? (y or n): ");
yes();
if (yes() == 1) {
printf("Please enter the contact's middle intial(s): ");
scanf("%s", (*contactName).middleInitial);
}
printf("Please enter the contact's last name: ");
scanf("%s", (*contactName).lastName);
}
I fixed the yes() code with
int yes(void) {
char singleLetter;
int theResults = 0;
scanf("%c", &singleLetter);
clearKeyboard();
while ((singleLetter != 'y') && (singleLetter != 'Y') && (singleLetter != 'n') && (singleLetter != 'N')) {
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
scanf("%c", &singleLetter);
clearKeyboard();
}
if ((singleLetter == 'y') || (singleLetter == 'Y')) {
theResults = theResults + 1;
}
if ((singleLetter == 'n') || (singleLetter == 'N')) {
theResults = 0;
}
return theResults;
}
i get this error. Literally makes me enter y 3 times, and i get a invalid entry code for no reason.
Do you want to enter a middle intial(s)? (y or n): y
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: y
y
Please enter the contact's middle intial(s):
EDIT PART 2
I fixed my function yes() by doing this:
int yes(void) {
char singleLetter = ' ';
int finalValue = -1;
int theResult = 0;
scanf(" %c", &singleLetter);
clearKeyboard();
do
{
switch (singleLetter)
{
case 'Y':
case 'y':
finalValue = 1;
theResult = 1;
break;
case 'N':
case 'n':
finalValue = 0;
theResult = 1;
break;
default:
theResult = 0;
printf("Only (Y)es or (N)o are acceptable: ");
scanf("%c", &singleLetter);
clearKeyboard();
}
} while (!theResult);
return finalValue;
}
And this is the code im not sure with NEAR THE END OF THE CODE:
void getName(struct Name *contactName) {
printf("Please enter the contact's first name: ");
scanf("%s", (*contactName).firstName);
printf("Do you want to enter a middle intial(s)? (y or n): ");
if (yes() == 1) {
printf("Please enter the contact's middle intial(s): ");
scanf("%s", (*contactName).middleInitial);
}
printf("Please enter the contact's last name: ");
scanf("%s", (*contactName).lastName);
}
// getAddress:
void getAddress(struct Address *
contactAddress) {
printf("Please enter the contact's street number: ");
(*contactAddress).streetNumber == getInt();
printf("Please enter the contact's street name: ");
scanf(" %[^\n]", (*contactAddress).street);
printf("Do you want to enter an apartment number? (y or n): ");
if (yes() == 1) {
printf("Please enter the contact's apartment number: ");
scanf("%d", (*contactAddress).apartmentNumber);
}
printf("Please enter the contact's postal code: ");
scanf(" %[^\n]", (*contactAddress).postalCode);
printf("Please enter the contact's city: ");
scanf("%s", (*contactAddress).city);
}
// getNumbers:
// getNumbers:
// NOTE: Also modify this function so the cell number is
// mandatory (don't ask to enter the cell number)
void getNumbers(struct Numbers *contactNumber) {
printf("Please enter the contact's cell phone number: ");
scanf(" %s", (*contactNumber).cell);
printf("Do you want to enter a home phone number? (y or n) ");
if (yes() == 1) {
printf("Please enter the contact's home phone number: ");
scanf("%s", (*contactNumber).home);
}
printf("Do you want to enter a business number? (y or n) ");
if (yes() == 1) {
printf("Please enter the contact's business phone number: ");
scanf("%s", (*contactNumber).business);
}
printf("\n");
}
AND BELOW THAT I HAVE THIS AND DONT KNOW WHAT TO DO. AS I STATED IN THE COMMENT:
The purpose of this function is to set the values for a Contact using
the pointer parameter variable (set the Contact it points to).
Use the pointer parameter received to this function to supply the appropriate
Contact member to the “get” functions (getName, getAddress, and getNumbers) to set the values for the Contact.
void getContact(struct Contact *contact) {
getName(contact);
getAddress(contact);
getNumbers(contact);
}
THE BELLOW IS WHATS BEING ACCESSED/PRINTED. Whatever i enter, it doesnt show up because of void getContact(struct Contact *contact){ }
getContact(&contact);
printf("\nValues Entered:\n");
printf("Name: %s %s %s\n", contact.name.firstName, contact.name.middleInitial, contact.name.lastName);
printf("Address: %d|%s|%d|%s|%s\n", contact.address.streetNumber, contact.address.street,
contact.address.apartmentNumber, contact.address.postalCode, contact.address.city);
printf("Numbers: %s|%s|%s\n", contact.numbers.cell, contact.numbers.home, contact.numbers.business);
scanf retains the newline \n in the buffer, the next time scanf is executed, the newline is read instead. Consider this program:
#include <stdio.h>
int main(void)
{
char x;
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
return 0;
}
The output for the input w<ENTER>s<ENTER>
w
119: 'w'
10: '
'
In ASCII 119 is 'w' and 10 is '\n'.
If you add a getchar() after the scanf, then getchar() reads the newline
and then nothing is in the buffer left, then the next scanf waits for the user input again:
#include <stdio.h>
int main(void)
{
char x;
scanf("%c", &x);
getchar(); // <-- look here
printf("%d: '%c'\n", x, x);
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
return 0;
}
with the same input I get
w
119: 'w'
s
115: 's'
So, to solve your problem, you can add a getchar() after every scanf.
The best way to clear the buffer after using scanf:
int c;
while((c = getchar() !='\n') && c !=EOF );
EDIT
How to use fgets
man fgets
#include <stdio.h>
char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and stores them into the buffer
pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into
the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
Simply to get a line, you do:
char line[1024];
fgets(line, sizeof line, stdin);
fgets will returns NULL when there is no more lines to read or there is an
error. Either way when that happens, you usually stop reading the file. That's
why to read all lines from a file (or multiple lines from the user), you do
this:
char line[1024];
while(fgets(lines, sizeof line, stdin))
{
// do the work here
}
Bear in mind, that sizeof line in fgets is only correct, when line is an
array. If you for example allocate memory with malloc, you cannot use
sizeof line. If you get a pointer, then you have to know in advance how much
you can read.
size_t n = <some value>; // the value is not imporant,
// could be 100, could be 985
char *line = malloc(n);
if(line == NULL)
{
// error handling, for example return error value
}
// only if line is not NULL
fgets(line, n, stdin); // here I know the size in advance
// or as argument
void foo(char *buffer, size_t size)
{
fgets(buffer, size, stdin);
...
}
If the length of the line is lesser than the size (minus 1) of the buffer, the
newline character will be stored in the buffer. If you don't need it, you can
set it to 0 in order to get rid of the newline:
char line[1024];
fgets(line, sizeof line, stdin);
int len = strlen(line);
if(line[len - 1] == '\n')
line[len - 1] = 0;
But if you don't mind having the newline, then you don't have to do that.
So you could write your yes function with fgets. Get the whole line, even
if you are only interested in the first character, you can ignore the rest of
the characters in the line.
#include <ctype.h>
int yes(void) {
int theResults = 0;
char line[1024];
if(fgets(line, sizeof line, stdin) == NULL)
{
fprintf(stderr, "could not get line, aborting\n");
return -1; // error value
}
while(toupper(line[0]) != 'Y' && toupper(line[0]) != 'N') {
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
if(fgets(line, sizeof line, stdin) == NULL)
{
fprintf(stderr, "could not get line, aborting\n");
return -1; // error value
}
}
if(toupper(line[0]) == 'Y')
theResults++;
else
theResults = 0;
return theResults;
}

Resources