I am trying to make a password generator. Everything was going smoothly until I tried to repeat the main function at the end. The code goes like this:
I also would appreciate feedback on the code. I am still learning (when do we stop learning though?) and I want to improve as much as I can and as fast as I can.
// password generator
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main ()
{
char answer;
int c=0;
int passlength;
char randLWUPchar; // lowercase, uppercase, characters + numbers
srand(time(NULL)); // seeding function
printf("Type the wished password length:");
scanf("%d", &passlength);
while(c < passlength){
randLWUPchar = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM"[rand () % 65];
printf("%c", randLWUPchar);
c++;
}
printf("\n\n\t\t...if it fails to prompt as wished, please restart...\n");
printf("\n\n\t\t Please select Y to restart or N to close");
scanf("%c", &answer);
if (answer == 'Y'){
return main();
}
else if (answer == 'N'){
return EXIT_SUCCESS;
}
}
I'd recommend refactoring your function to not use recursion.
With optimizer on full blast this tail call should be easy to optimize out, but you shouldn't be depending on the optimizer. Use a loop instead.
Try something like:
do
{
// your code
} while(answer == 'Y');
return ERROR_SUCCESS;
Contrary to what is said in comments, yes, your main() can be recursive.
As mentionned by #Keith Thompson, you must flush the '\n' after reading your passlength. For example:
scanf("%d", &passlength);
fgetc(stdin);
Then
scanf("%c", &answer);
fgetc(stdin);
Related
I'm new to C and this is my TicTacToe for first C project. For that, I setup a simple process for user where to choose X or O. But it doesn't seem to work for reason. Here it continues to the if statements and goes into infinite loop cause it didn't wait for user input.
I've gone through similar forums about this exact question but I was unable to get an answer that fixed my problem. Also, feedbacks about the code are much appreciated because I do want to improve my code.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char checks_player;
int is_input_valid = 0;
while(is_input_valid == 0)
{
printf("What do you want to choose? (X/O) ");
scanf(" %c",checks_player);
if(checks_player == 'x')
{
checks_player = 'X';
is_input_valid = 1;
}
else if(checks_player == 'o')
{
checks_player = 'O';
is_input_valid=1;
}
else if((checks_player == 'O')|| (checks_player == 'X'))
{
is_input_valid = 1;
}
else
{
printf("Invalid Input!!\nTry Again.\n\n");
}
}
}
You need to pass a pointer to scanf. Instead of this:
scanf(" %c",checks_player);
Use this:
scanf(" %c", &checks_player);
How do I make a program shut itself down after user says y in case 3. I want when they press y in case 3 that program exits it self like it would when compiling is done. I'm trying to make a menu where you can browse trough the options its not complete yet I need to make play, graphics, sounds case. Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int main()
{
int op1;
printf("1.Play\n");
printf("2.Options\n");
printf("3.Exit\n");
scanf(" %d", &op1);
char ans;
switch(op1)
{
case 1 : printf("Press 5 to start a new game");
break;
case 2 : printf("1.Graphics\n"); printf("2.Sound\n");
break;
case 3 : printf("Are you sure (y/n)");
scanf(" %c", &ans);
if(ans =='y')
{
}
else
{
printf("1.Play\n");
printf("2.Options\n");
printf("3.Exit\n");
}
default : printf("Wrong choice.");
}
return 0;
}
If this is to be restricted to the main() method, then just return out.
if(ans == 'y') {
return 0;
}
It is a good practice to avoid hard exits unless you really need them.
But if you really need to hard exit out, you may try _exit(0); here. exit(0); as well, which has already been mentioned.
First of all, y is not a variable, you have to compare with the character code:
if (ans == 'y') {...}
To terminate your program, use:
exit(0);
This is the first question I've posted about C programming on here as I just started learning C just a few weeks ago. Ill write up my code and ask what my problem is :) If Anyone please knows how I can fix my mistake or whatever I should replace for my code please reply:)!
The problem I am having, is that if you run the code for yourself, you will see that everything works fine, except for the 'else' part in the statement. The issue I am having is that when someone types more than one letter, it will run the last printf statement more than once, and will printf as many times as the user inputs a character other than y or n.
The first part with the Y or N is working fine, yet if they type any number of other chars, it doesnt just state "Please select again", one time and then re-scanf, it types out at least 2 printfs, just for even one character entered, "Please select again" "Please select again", and then, if you type more chars for the answer, it will just type even more "please select again"'s.
Please help me understand what I am doing wrong as I'm so keen on learning to program properly, but I am just stuck here atm :)
#include <stdio.h>
#include <conio.h>
int main()
{
char answer;
int loop = 0;
printf("Please select. [Y/N]:\n");
while (loop == 0)
{
scanf("%c", &answer);
if (answer == 'y' || answer == 'Y')
{
printf("Seeyou Later Aligator.\n");
break;
return 0;
}
else if (answer == 'n' || answer == 'N')
{
printf("Mmkay.\n");
break;
return 0;
}
else
{
printf("Please select again [Y/N]:\n");
loop = 0;
}
}
getch();
return 0;
}
scanf reads the required number of characters each time. If there are more characters, they are not ignored. They are read next time you call scanf. Hence you see multiple prints for every character. Inorder to explicitly ignore pending input, call fflush(stdin) after scanf. Which means to flush out any data in standard input stream.
Update:
fflush should not be used on input streams as said in comments. Use the accepted solution for ignoring output. However I recommend using toupper or tolower instead of bit hack.
The reason as many have pointed out is that your scanf is reading the extra newline character left in the input buffer after the user presses ENTER. So here is an alternative way to read input to avoid that whole mess:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char answer;
printf("Please select. [Y/N]:\n");
while (1)
{
scanf("%1s%*[^\n]", &answer);
answer |= 0x20;
if (answer == 'y')
{
puts("Seeyou Later Aligator.");
break;
}
else if (answer == 'n')
{
puts("Mmkay.");
break;
}
else
{
puts("Please select again [Y/N]:");
}
}
getchar();
return 0;
}
This will read just the first character found on stdin and ignore everything else after that and at the same time clear the input buffer of the newline character
break; is enough ... return will never be executed as you will break out of the while
Its printing more than once because scanf is taking in '\n' and extra inputs from previous entry
also the variable loop is pointless in your code
here is the fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char answer;
int loop = 0;
printf("Please select. [Y/N]:\n");
while (1)
{
scanf("%c", &answer);
if (answer == 'y' || answer == 'Y')
{
printf("Seeyou Later Aligator.\n");
break;
//return 0;
}
else if (answer == 'n' || answer == 'N')
{
printf("Mmkay.\n");
break;
// return 0;
}
else
{
printf("Please select again [Y/N]:\n");
while(getchar()!='\n'){
getchar();
if(getchar() == '\n'){
break;
}
}
}
}
getchar();
return 0;
}
Output:
$ ./test
Please select. [Y/N]:
dddd
Please select again [Y/N]:
ffffff
Please select again [Y/N]:
y
Seeyou Later Aligator.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
This simple program asks the use's age and based on that displays a message.At the end if it,the user is asked if he would like to repeat the whole thing again.But I am getting the error
Break statement not within loop or switch
when I compile it. What does that mean and how do I correct it?
#include <stdio.h>
#include <string.h>
static int prompt_continue (const char *prompt)
{
printf("%s", prompt);
char answer[5];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
int c;
while ((c = getchar()) != EOF && c != '\n')
;
return 1;
}
return 0;
}
int main(void)
{
/*Creates a simple program using if else example. */
int age;
while (printf("Welcome, this program is designed for if else statements.\n"));
printf("Please enter your age.\n");
scanf (" %d", &age); /*Enters age.*/
if (age < 18){
printf("You are young!\n");
}
else if (age > 18){
printf("Ah you're old!\n");
}
{
printf(" Woot.\n");
if (prompt_continue("Do you want to try again? Y/N") == 0)
break;
}
return 0;
}
Just trying to work through this, need a little help. Did I use the while loop wrong? Any thoughts would be helpful. Thanks!
You need to define the scope of your loop. In this code:
while (printf("Welcome, this program is designed for if else statements.\n"));
printf("Please enter your age.\n");
...
if (prompt_continue("Do you want to try again? Y/N") == 0)
break;
what you actually need is:
while (true)
{
printf("Welcome, this program is designed for if else statements.\n"));
printf("Please enter your age.\n");
...
if (prompt_continue("Do you want to try again? Y/N") != 1)
break;
}
break stops the execution of while loop here.
The problem is that your break statement does nothing because it is not in a loop or switch, why did you put it there.
It's just what your error say!!break statement has to be within the body of a loop , if or switch-case and takes the control out of that block.This is what you should use here instead of break if you want to end the program at that point:
exit(0); //0 means successful termination, non-zero value means otherwise.
I am afraid your program needs an overhaul if you want the whole thing to repeat again.The logic is faulty.Let me check...
Edit Well,here's your full working program.I am sure you will understand the changes made.Else tell your confusions (if any) in a comment.Here's a brief explanation of the changes:
Th return statements in your prompt_contineu() function needed a little change,the getchar() there was not needed at all, there was no condition in the while loop in the main() function and its body was not well defined within {}, and last but not the least, the prompt_continue() function needed to be invoked within the while loop to get the job done.I hope you can see what the continue statement does. By the way this evil program said I am FRIGGIN OLD :-)
#include <stdio.h>
#include <string.h>
static int prompt_continue (const char *prompt)
{
printf("%s", prompt);
char answer[5];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
return 2;
if (answer[0] == 'n' || answer[0] == 'N')
return 3;
}
return 0;
}
int main(void)
{
/*Creates a simple program using if else example. */
int age;
while (1)
{
printf("Welcome, this program is designed for if else statements.\n");
printf("Please enter your age.\n");
scanf (" %d", &age); /*Enters age.*/
if (age < 18)
printf("You are young!\n");
else if (age > 18)
printf("Ah you're old!\n");
printf(" Woot.\n");
if(prompt_continue("Do you want to try again? Y/N")==3)
break;
else
continue;
}
return 0;
}
This simple issue is causing my entire program to crash during the first input. If I remove the input, the program works fine but once I add scanf into the code and enter the input the program crashes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXEMPS 3
// stub program code
int main (void){
char answer;
do
{
printf("\n Do you have another(Y/N): ");
scanf("%c", answer);
}while(answer == 'Y' || answer == 'y');
getchar();
printf(" Press any key ... ");
return 0;
} // main
You must pass the address of the variable to scanf:
scanf("%c", &answer);
Use "&answer". And get rid of the extraneous "fflush()" commands...
Better, substitute "answer = getchar ()".