Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Given a int variable named yesCount and another int variable named noCount and a char variable named response, write the necessary code to read a value into into response and then carry out the following:
if the character typed in is a y or a Y then increment yesCount and print out "YES WAS RECORDED"
if the character typed in is an n or an N then increment noCount and print out "NO WAS RECORDED"
if the input is invalid just print the message "INVALID" and do nothing else.
Hello, I am having trouble with my C code for this problem. I'm getting incorrect outputs. Any assistance is much appreciated. Thank you.
if (response == 'y' || response == 'Y') {
scanf("%d", &yesCount);
yesCount++;
printf("YES WAS RECORDED");
}
if (response == 'n' || response == 'N') {
scanf("%d", &noCount);
noCount++;
printf("NO WAS RECORDED");
} else {
printf("INVALID");
}
There might be some typo here because I'm writing from my smartphone. Be aware of that. By the way here as how I would do that :
#include <stdio.h>
int main(void) {
int yescount = 0, nocount = 0;
int c;
while ((c = getchar) != EOF) {
switch (c) {
case 'y':
case 'Y':
puts("Yes registered");
yescount++;
break;
case 'n':
case 'N':
puts("No registered");
nocount++;
break;
default:
puts("Invalid selection.");
break;
}
}
return 0;
}
You should learn how to present your code correctly: it helps a lot with readability and makes many bugs more visible.
There are problems with your code:
You call scanf for no purpose, but you do not read the response as requested.
You forgot an else at the end of the body of the first if. The consequence is that the last else branch is taken if the response is y or Y.
You should probably print a \n after each message so it appears separate from the subsequent output.
Here is a corrected version:
scanf("%c", &response);
if (response == 'y' || response == 'Y') {
yesCount++;
printf("YES WAS RECORDED\n");
} else
if (response == 'n' || response == 'N') {
noCount++;
printf("NO WAS RECORDED\n");
} else {
printf("INVALID\n");
}
From your comment, they expect you to use scanf("%c", &response); to read the char into response, not the simplest way to read a byte from stdin.
Related
This question already has answers here:
Most efficient way to compare a variable to multiple values?
(7 answers)
Closed last year.
I have been struggling to get my if statement in my function to evaluate correctly. I am attempting to get the if statement to evaluate as true only if the variable is equal to 'Y' or 'y'. I am new to messing with char variables, so my suspicion is I am either storing chars into the variable incorrectly, or evaluating the expression in a way that is always true.
The code I wrote is the following:
#include <stdio.h>
// fuctions
int Greeting(void);
// variables
int return_status;
int main(void)
{
return_status = Greeting();
printf("Return status is %d \n", return_status);
return 0;
}
int Greeting(void)
{
char status;
printf("Welcome to the program. Would you like to continue?(Y/N)\n");
scanf(" %c", &status);
if (status == 'Y' || 'y') // Problem is probably here
{
printf("You have said %c.\n", status);
return 0;
}
else
{
return 1;
}
}
The first comparison you wrote here is correct, but the expression you wrote to the right of the statement is not a comparison. You directly write the expression 'y' there, since it does not correspond to 0 in the ASCII table, it is considered true and always gives the true result when combined with the OR expression.
if(status == 'Y' || 'y')
You should change like this;
if((status == 'Y') || (status== 'y'))
if((status == 'Y') || (status == 'y')) //Problem is probably here
{
printf("You have said %c.\n", status);
return 0;
}
You can check char like that
Yes, the problem is the "if" statement. You have to write:
if (status == 'Y' || status == 'y')
Variable return_status should be declared into main() function.
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);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am new to the C programming language and I've been trying to make a little text-based game in it. The input is very simple, as the user needs to input S or s and N or n.
The problem is, when I run the program and feed input to choice, the program simply stops working.
Here's the code:
/*O jogo */
#include <stdio.h>
#include "story.h"
int main() {
char choice;
puts(intro);
scanf("%c", &choice);
if (choice == 's' || choice == 'S') {
puts(dialog0);
puts(dialog1);
puts(dialog2);
puts(dialog3);
puts(dialog4);
puts(dialog5);
scanf(" %c", &choice);
if (choice == 's' || choice == 'S')
puts(dialog6option1);
else if (choice == 'n' || choice == 'N') {
puts(dialog6option2);
puts(dialog6option2pt2);
}
puts(dialog6);
puts(dialog7);
puts(dialog8);
puts(dialog9);
puts(dialog10);
scanf(" %c", &choice);
if (choice == 's' || choice == 'S') {
puts(dialog10option1);
puts(dialog10option1pt2);
} else if (choice == 'n' || choice == 'N') {
puts(dialog10option2);
puts(dialog10option2pt2);
}
}
return 0;
}
The program I compiled does not "stop working" (I filled in the missing strings). It simply exits when I enter 'n' at the first response, because, to summarise, it is like this.
int main() {
char choice;
puts(intro);
scanf("%c", &choice);
if (choice == 's' || choice == 'S') {
// ...
}
return 0;
}
So 'n' simply exits the program, otherwise when I start with 's' and then continue with 'n' or 's' I get the printed dialogs. Although as I commented above, what is supposed to happen when neither 'n' or 's' are entered?
BTW you have no prompts to help the user know what they are supposed to enter, or why.
The behavior of scanf is interesting especially when you include whitespace in the format string. When I wrote more console-oriented applications and wasn't using something like curses, I used a function like the following to read input:
char
get_next_input(void)
{
int ch;
while ((ch=getchar()) != EOF) {
if (!isspace(ch)) {
return (char)ch;
}
}
return (char)'\0';
}
It returns the next non-whitespace character in the stream or '\0' on EOF. I found it more reliable than using scanf across various implementations.
The problem that you are probably experiencing is line buffering on stdin. The call to scanf might not return until you press enter (e.g., enter a newline character).
You're missing a space within your first scanf:
...
puts(intro);
scanf(" %c", &choice); /* missing the space in your code*/
...
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;
}