This may be a simple answer. I have only been programming with C for a month.
I am creating a C-program that the user is presented with a menu 1-4.
Menu options 1-3 ask the user for an integer, when an integer is input, the program writes or "draws" that amount of "dots" or periods.
Each of the first options will do the same function, but a while loop, do-while loop, and a for loop respectively.
The only way to terminate program is to select 4 at the main menu.
My question is how to get my program to loop back and continue to work properly.
When i execute the program it works correctly the first time, but when the program loops back to the main menu. No further options work. IE: if i try the input an integer again for the "dot drawing" it doesnt work correctly.
I am also Having trouble validating input on either menu for letters or "non numbers", at the moment if you input a letter it breaks the program.
Im not sure what to do and where to go with this.
Im not needing the code re-written, perhaps just some ideas of where to take it.
I'll accept any references or links provided.
a copy of my incomplete program is included below:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
system("cls");
int programRun=0;
int menuSelection=0;
int absmenuSelection=0;
int dotNumber=0;
int countNumber=0;
char enter;
while(programRun==0)
{
system("cls");
printf("\nplease make a number selection\n");
printf("Please select a choice:\n");
printf("[1] While loop...\n");
printf("[2] Do-While loop...\n");
printf("[3] For loop...\n");
printf("[4] Exit program...\n\n");
scanf("%d%c",&menuSelection,&enter);
absmenuSelection= abs(menuSelection);
if (absmenuSelection <1 || absmenuSelection>4)
{
}
switch (absmenuSelection)
{
case 1:
printf("\nPlease input a number for the amount of dots you wish to see...");
scanf("%d", &dotNumber);
if(dotNumber > 0)
{
while(countNumber<dotNumber)
{
countNumber++;
printf(".");
}
}
else{
printf("\nsorry, that is an invalid response. Now you have to try again.\n");
}
printf("\n");
system("pause");
break;
case 2:
printf("\nPlease input a number for the amount of dots you wish to see...");
scanf("%d", &dotNumber);
if(dotNumber > 0)
{
do
{
countNumber++;
printf(".",countNumber);
}
while( countNumber<dotNumber );
}
else
{
printf("\nsorry, that is an invalid response. Now you have to try again.\n");
}
printf("\n");
system("pause");
break;
case 3:
printf("\nPlease input a number for the amount of dots you wish to see...");
scanf("%d", &dotNumber);
if(dotNumber > 0)
{
for(countNumber=0;countNumber<dotNumber;countNumber++)
{
printf(".",countNumber + 1);
}
}
else
{
printf("\nsorry, that is an invalid response. Now you have to try again.\n");
}
printf("\n");
system("pause");
break;
case 4:
while(programRun>1)
programRun=1;
printf("\nOkay have a nice day");
return 0;
default:
printf("\nsorry that is an invalid statement, try again\n\n");
system("pause");
}}
system ("pause") ;
return 0;
}
its working well .....
Set after each case: countNumber=0;
or try
if(dotNumber > 0)
{
countNumber=0;
/*REST */
}
otherwise case 1: case 2: will not work if i try 2 times after giving dotNumber a higher value at first and lower at last
EDIT:
The C library function void isdigit(int c) checks if the passed character is a decimal digit character.
if( isdigit(variableHere) )
{
//is a digit
}
Sample o/p
please make a number selection
Please select a choice:
[1] While loop...
[2] Do-While loop...
[3] For loop...
[4] Exit program...
1
Please input a number for the amount of dots you wish to see 4
....
Press any key to continue . . .
Related
I'm having a problem understanding how to get my while loop to simply output a message saying "Invalid Input" and asking for a new question from the user unless he chooses number 1 or 2 in the list. What happens if you for example input : asdas instead of a integer the program never stops looping.
What I would like to happen is for the program to tell the user to enter a new number from 1-2 instead of simply stopping running which i can achieve by setting the default in the switch to exit(0); or runSystem = false;
For example:
CMD Says enter 1-2 the user enters : asdaf (never stops looping) as in current situation.
What I want is: asdf and then it says "enter a new choice" and waits for a correct answer.
What bothers me is the fact that the program will do as i want it to if you enter an invalid number for example: 12312312 and ask for a new entry but it doesn't work with string input.
Code:
#include <stdio.h>
#include <stdbool.h>
int main(int argc, char **argv) {
int userinput;
int runSystem = true;
void options() {
printf("<========Welcome to the program, please make a choice========> \n\n");
printf("1: Say Hello\n");
printf("2: Say GoodBye\n");
printf("Please enter a choice:");
scanf("%d", &userinput);
}
while (runSystem) {
options();
switch(userinput) {
case 1: printf("Hello!\n");
break;
case 2: printf("GoodBye!\n");
break;
case 3: printf("Invalid, try again\n");
break;
default:
break;
}
}
return 0;
}
scanf("%d", &userinput); expects an int as the input. When you give a non-integer, scanf() won't assign it to userinput.
Check the return value of scanf() to see if it was successful. It returns the number of successful assignments it did.
When you give a string as input, scanf() won't accept it and will leave it in the input buffer unconsumed.
When you do scanf() again, the invalid input is still present in the input buffer and that is what the second scanf() tries to read. The same thing happens and this goes on. This is the reason behind your infinite loop.
To overcome this, you should consume the invalid input from the input buffer after displaying the message in case 3. Do something like
int ch;
while( (ch=getchar())!='\n' && ch!=EOF );
This will consume from the input buffer till a \n is encountered. getchar() return EOF on failure.
Edit: Standard C doesn't allow nested function definitions. The reason why you didn't get an error for that is probably because your compiler allows this as an extension. But it may not work for other compilers.
See this and this.
You could place the definition of options() within the while loop calling it or get the value for userinput as a return value or via a pointer to the variable passed to the function.
Valid C compiler does not allow declaration of the function options inside the main.
Make that function returning your input and pass the returning value to the switch. Also in order to stop the while loop case 2: should change the runSystem to false;
input : asdas instead of a integer the program never stops looping.
This is because when scanf("%d", &userinput); failed it did not updated the variable userinput.
Check the standard 7.21.6.4 The scanf function.
You can read about behaviour of scanf
here.
On success, the scanf returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.
Knowing that you can check the return value of scanf and make appropriate decision. Presented solution eats the bad characters.
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
int options(void) {
int c;
int ret;
int x = 0;
int error = 0;
printf("<========Welcome to the program, please make a choice========> \n\n");
printf("1: Say Hello\n");
printf("2: Say GoodBye\n");
printf("Please enter a choice:");
while(1)
{
c = '0';
if(!error)
printf("Input a number:\n");
else
error = 0;
ret = scanf("%d", &x);
if(ret == EOF) {
return 2; // END OF PROGRAM
}
else
{
if (ret == 1){
return x;
}
else // NOT a number
{
printf("No letters! Input a number:\n");
do
{
c = getchar();
if(c == EOF)
return 2; // END OF PROGRAM
}
while (!isdigit(c) && c!='\n');
ungetc(c, stdin);
error = 1;
}
}
}
}
int main(void) {
int userinput;
int runSystem = true;
while (runSystem) {
userinput = options();
switch(userinput) {
case 1: printf("Hello!\n");
break;
case 2: printf("GoodBye!\n");
runSystem = false;
break;
default:
case 3: printf("Invalid, try again\n");
break;
}
}
return 0;
}
Output:
<========Welcome to the program, please make a choice========>
1: Say Hello
2: Say GoodBye
Please enter a choice:Input a number:
X
No letters! Input a number:
a
No letters! Input a number:
1
Hello!
<========Welcome to the program, please make a choice========>
1: Say Hello
2: Say GoodBye
Please enter a choice:Input a number:
7
Invalid, try again
<========Welcome to the program, please make a choice========>
1: Say Hello
2: Say GoodBye
Please enter a choice:Input a number:
2
GoodBye!
I'm making a menu that lists options 1-3. The user is expected to enter an integer.
scanf("%d", &select_option)
How do I prompt error when user enters a char (for example "a", or "asd" for long strings, or a mixture like "1a2") instead of an expected int? Thanks.
Note: When the user enters a 'char' like 'a', 'asd', the code goes into an infinite loop for some reason.
Here's my program (minimal example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
while(select_option != 4)
{
switch(select_option)
{
case 1:
printf("You like tennis! Nice! \n");
break;
case 2:
printf("You like badminton! Nice!");
break;
case 3:
printf("You like basketball! Nice!");
break;
default:
system("clear");
printf("Invalid option. Please re-enter your choice (1-4).\n");
}//end switch
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
}//end while
}//end main
You could do this:
#include <stdio.h>
int main(void) {
int v;
int ret = scanf("%d", &v);
if(ret == 1)
printf("OK, %d\n", v);
else
printf("Something went wrong!\n");
return 0;
}
where I took advantage of the return value of scanf(), and based on that value, I made an assumption. This will fail for the case of "1a2", but will succeed for "12" and "a".
However, this is a broad question and personally the way I would go for it is:
Use fgets() to read input.
Discard newline.
Convert string to integer (with strtol() for example).
Validate input.
I am assuming u are a beginner. You can use Switch Case which is used usually for creating menus and depending on the choice of the user executes the particular case.
I will show u a small example.
#include<stdio.h>
#include<conio.h>
int main()
{
int n;
printf("Select the sports u want to do\n");
printf("1.Tennis\n2.Karate\n3.Football\n");
scanf("%d",&n);
Switch(n)
{
case 1:printf("You chose Tennis\n");
break; //To prevent from all cases being executed we use
//break which helps from coming out of a loop
case 2:printf("You chose Karate\n");
break;
case 3:printf("You chose Football\n");
break;
default:printf("Please enter an appropriate number !");
//Cases which dont match with the input are handled by default !
}
}
Also to make the user enter input until he wants to exit add a while loop with a variable !
I hope this helps!
#include <stdio.h>
void load_menu(void);
int main(void)
{
load_menu();
return 0;
}
void load_menu(void)
{
int choice;
int loopagain;
do
{
printf("Menu \n\n");
printf("Please enter your choice: \n");
printf("1. \n");
printf("2.\n");
printf("3.\n");
printf("4. Exit\n");
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4: printf("Quitting program!\n");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
printf("Characters are invalid, please enter a number: \n ");
if (scanf("%d",&loopagain)==1)
load_menu();
}
}while((choice !=4));
}
why is this still giving me an infinite loop when I enter a character? It is a menu (the case statements still need to be filled) but i am taking care of the character input by the if statement but it still does not seem to work. Thanks
If the character input is invalid, the loopagain in the newly-called load_menu() won’t be the same as in its caller. Don’t recurse at all:
else
{
printf("Characters are invalid, please enter a number: \n ");
choice = 0; // Unused, so continue the loop
}
I believe, aside from the problems identified so far, is that the offending "letter" is stuck in the input buffer. When reading a number with scanf, it stops as soon as it hits anything not whitespade and not a digit. So if the buffer contains "a\n", and we call scanf("%d", ...), then scanf will return immediatelty, and will keep on doing so until the offening 'a' has been removed from the buffer.
What we need is a little loop to remove the offending "rubbish" from the input buffer.
Here's that question asked before (although the flushing is for a slightly different reason, the solution is the same):
Question about flushing buffer
After you enter something the is not a digit, and as such is not accepted by scanf("%d",&choice) the input buffer is not flushed. I believe you should be able to fix this issues with a call to fflush(stdin) when handling unacceptable inputs. Better, you would probably be better servde to flush the input buffer after each time you call scanf.
To my mind, your handling of an incorrect input doesn't make sense. It should be handled more like your default: case, I think. The recursive call, as has been stated by others, doesn't make sense, nor does calling scanf again for input when you are about to go back to displaying the menu and getting user input yet again.
I think your problem is the loopagain variable. By the name, you were thinking about this variable like a flag to loop or not again and to manage the way your second loop would go. Since you are reading it from stdin(scanf) you'll lost the control over it.
Since you already have one scanf in your implementation and since it is a loop, you won't need recursive calls and you can use always the same scanf, using the loopagain variable/flag in the proper way.
Even better is that in this way, there's no char wich its integer value is 4(it woul never pass the scanf test with value 1, but still...) besides the EOT (ascii - cntr-D) wich is a non-common one, and you can think of it as an alternative way to break your program.
One soluiton is this(I guess, by my interpretation) :
#include <stdio.h>
void load_menu(void);
int main(void)
{
load_menu();
return 0;
}
void load_menu(void)
{
int choice;
int loopagain = 1;
do
{
if(loopagain != 0){ /*You'll set it to different from 0 if the user entered a 'bad' number so the menu is only printed once*/
printf("Menu \n\n");
printf("Please enter your choice: \n");
printf("1. \n");
printf("2.\n");
printf("3.\n");
printf("4. Exit\n");
}
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4: printf("Quitting program!\n");
break;
default:printf("Invalid choice! Please try again\n");
loopagain = 0;
printf("\n");
break;
}
}else{
printf("Characters are invalid, please enter a number: \n ");
loopagain = 0;
}
}while(choice !=4);
}
Hope it helped.
My goal is to produce a program that will take a file as input and "encode" the text within by shifting the characters ahead 3 (so 'a' would be come 'd'). It should produce an output file with the encoded text. The menu is to take user input and execute the function that is assigned to the number selected.
I'm early on at creating this program, but running short on time and am struggling with how to structure it. Currently, I have the menu displaying, but when a sub function is called, it displays but then the menu overwrites it and I can't figure out why. Any help would be appreciated. Here is the code I have so far...
#include <stdio.h>
#define INPUT_FILE 1 //define statements
#define OUTPUT_FILE 2
#define NUM_TO_SHIFT 3
#define ENCODE 4
#define QUIT 0
int menu(); //function prototypes
int input();
int output();
int shift();
int encode();
void quit();
int main()
{
int choice; // main variables
char user_filename[100];
choice = menu(); // get user's first selection
while(choice != QUIT) //execute so long as choice is not equal to QUIT
{
switch(choice)
{
case INPUT_FILE:
printf("Enter the filename of the file to encode:\n");
printf("(hit the Enter key when done)\n");
gets(user_filename);
break;
case OUTPUT_FILE: output();
break;
case NUM_TO_SHIFT: shift();
break;
case ENCODE: encode();
break;
case QUIT: quit();
break;
default: printf("Oops! An invalid choice slipped through. ");
printf("Please try again.\n");
}
choice = menu(); /* get user's subsequent selections */
}
printf("Bye bye!\n");
return 0;
}
int menu(void)
{
int option;
printf("Text Encoder Service\n\n");
printf("1.\tEnter name of input file (currently 'Secret.txt')\n");
printf("2.\tEnter name of output file (currently not set)\n");
printf("3.\tEnter number of characters data should be shifted (currently +7)\n");
printf("4.\tEncode the text\n\n");
printf("0.\tQuit\n\n");
printf("Make your selection: ");
while( (scanf(" %d", &option) != 1) /* non-numeric input */
|| (option < 0) /* number too small */
|| (option > 4)) /* number too large */
{
fflush(stdin); /* clear bad data from buffer */
printf("That selection isn't valid. Please try again.\n\n");
printf("Your choice? ");
}
return option;
}
int input()
{
}
int output()
{
return 2;
}
int shift()
{
return 3;
}
int encode()
{
return 4;
}
void quit()
{
printf("Quiting...Bye!");
exit(0);
}
You shouldn't use gets(user_filename) to get the file name since gets() reads up to a \n and stops reading. Your scanf for the menu option does not read the \n at the end of the line when the user types in the menu option. Essentially, you're making gets read a string without words in it. The line you want to read is actually the next line. Using scanf instead of gets will fix it.
Otherwise, your program is working as expected - it's just that your functions don't do anything yet that your menu is "overwriting" the submenus. See http://ideone.com/F2pEs for an implementation with scanf instead of gets.
use getchar(); soon after the gets(user_filename); it will wait to get the character
gets(user_filename);
getchar();
break;
As in this question which Stackoverflow has highlighted as a match, you need to clear out the buffer to remove the newline that's waiting in there.
Add this code after reading a valid menu option:
do
{
c = getchar();
} while (c != EOF && c != '\n');
where c is a char declared up by option. This loops over remaining characters in the input stream until EOF (End Of File) or a newline character is reached, meaning they don't affect your call to gets(). Note that gets() is considered insecure because it doesn't protect against buffer overflow, a user could easily enter more than 100 characters (inc. newline) and start writing into memory that shouldn't be touched by their input. You would do well to lookup the secure equivalent when you see compiler warnings around function calls like this, typically they take a second parameter which is the maximum size of the buffer being read into.
Well, this answer is way late but having come across it, I can't help but write something.
Let's get straight to it. You will have an array of menus, with the array elements being the options you want in your menu. Then while in a truthy condition, loop through the elements of the array, selecting the option you want.
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
//function prototypes
int input();
int output();
int shift();
int encode();
void quit();
int main(){
int menus_on = 1;
const char *menus[5] = {"Input","Output","Shift","Encode","Quit"};
while(menus_on){
int menu,*temp;
for(int i =0;i<6;i++){
printf("%d: %s\n",i,menus[i]);
}
printf("Select menu\n");
scanf("%d",temp);
menu = *temp;
printf("Selected menu::%d\n",menu);
switch(menu){
case 0:
input();
break;
case 1:
output();
break;
case 2:
shift();
break;
case 3:
encode();
break;
case 4:
quit();
break;
default:
printf("Invalid selection\n");
break;
}
}
return 0;
}
int input() {
return 0;
}
int encode () {
return 0;
}
I'm currently working on a program that asks a user to enter a secret word. The user's input is then compared with a list of words which are on a text file. The user has 3 chances to enter the word. If correct, the program restarts the loop. This continues until all the words have been guessed correctly. If a word is incorrectly guessed 3 times, the program should terminate. My problem is with the 3 guesses loop. I can get it to work if it is not nested in the while loop however with the while loop it's continues to ask for the incorrect word. What am I missing? Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
//Step 1: open file and declare variables//
FILE *fp;
fp = fopen("secretwords.txt","r");
char guess[20];
char secret[20];
int i;
//Step 2: Check that file opened correctly, terminate if not//
if (fp == NULL)
{
printf("Error reading file\n");
exit (0);
fclose(fp);
}
//Step 3: Create loop to run for each word to run to end of file//
while(fscanf(fp,"%s", secret)!=EOF)
{
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct\n");
break;
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
}
return 0;
}
When you do break, you break from the for loop, but not from the while loop.
To solve it, you can either change the design to have one loop only, or you should have the break instruction in the outer loop too.
You did not do break in the following part:
else
{
if(i == 2)
break;
printf("Your guess was incorrect. Please try again\n");
}
Hint: if the user has had 3 misses, the value of i after the for loop will equal to 3. This is your chance to do something (terminate the program).