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);
Related
I Have written a simple while program in C
// Online C compiler to run C online.
// Write C code in this online editor and run it.
#include <stdio.h>
typedef enum
{
false = 0,
true = 1
} bool;
int main() {
bool res = true;
while (res)
{
char choice;
printf("Success! \n");
printf("Do you want to continue(y/n): ");
scanf("%c", &choice);
if (choice == 'N' || choice == 'n')
{
res = false;
}
}
printf("Good Bye");
}
The Program run successfully but when I type Y in Do you want to continue the loop is executed twice. How Can I Solve this?
Add a space before %c in scanf it skip all whitspaces(newline) like
scanf(" %c", &choice);
^
when I type Y in Do you want to continue the loop is executed twice ?
When you type Y+enter this will go like "Y\n" and this new line will taked by next iteration, so use above meathod to discard it.
Similiar Questions :
1)scanf() leaves the new line char in the buffer
Thanks.
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);
I have a problem with my input for my program:
#include <stdio.h>
#include <stdlib.h>
int confirm()
{
char c;
printf("Confirm (y/n): ");
scanf("%c", &c);
while (scanf("%c", &c))
{
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')
{
printf("\nThank you. \n");
break;
}
else
{
printf("\nInput not recognised, ry again. \n");
printf("Confirm (y/n): ");
}
}
}
int main(int argc, char* argv[])
{
confirm();
return 0;
}
When it executes, it asks the first question and inputting the answer is fine. However after entering the character (either y or n) the program prints the second question and stops. The whole program is not running. I don't know what I'm doing wrong.
Loose the first scanf at line 9 and (for me) it then seem to work correctly: if ynYN is entered then the confirm function exits, otherwise it continues looping
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;
}