Currently completing a programming assignment where at the beginning of the program I want the user to enter an integer as a way to select a menu item. I have made efforts to implement some degree of input checking such that the program checks if the input is 1 of the 2 menu numbers. However, even when I enter in a valid input this fails to be picked up and the program identifies it as an invalid input.
My code is as follows:
#include <stdio.h>
#include <math.h>
#include <string.h>
#define WIDTH 15
#define HEIGHT 15
#define NAMELENGTH 128
int main() {
//int actGrid[HEIGHT][WIDTH];
//int nextGrid[HEIGHT][WIDTH];
char name[NAMELENGTH];
printf("Welcome to Conway's Game of Life. To Begin, What Is Your Name?\n");
scanf("%[^\n]%*c", name);
int menSelect;
printf("Hello %s, Please Enter the Integer Next to the Item Below That Describes How You Would Like Your Game of Life to Initially Be Set Up\n \n 1. Gosper's Glider Gun \n 2. R-Pentomino\n ", name);
for(;;){
int checkIn=scanf("%d",&menSelect);
if(checkIn!=1){
fprintf(stderr,"Scanf Has Failed to Read In Any Values\n");
}
if(menSelect!=1 || menSelect!=2){
fprintf(stderr,"%s, %d Is Not a Valid Selection\nPlease Try Again\n",name,menSelect);
}else{
break;
}
}
return 1;
}
I honestly am quite stumped by this as the scanf function apparently reads the correct value in but then it gets dealt with as though it didn't.
your code is perfect except || in the 'if' condition. || returns true if at least one condition is true. When menSelect is equal to 1, it is not equal to 2 and hence, 'if' condition evaluates to true. Using && solves the problem. If menSelect equals to 1, then the 'if' condition fails and evaluates to false
if(menSelect!=1 && menSelect!=2){
fprintf(stderr,"%s, %d Is Not a Valid Selection\nPlease Try Again\n",name,menSelect);
}
Hope it helps!
Related
Just tried to write a program (in C) where the computer picks a random number between 0 and 9, and the user keeps guessing until they get it. I wrote is as an if...else if...else statement, and for some reason, no matter what the input is, the else statement always comes back.
For example, if I input '2', the program will say both "Oof, nice try. But try again!" AND "You need to enter a digit!" which is supposed to be the output when you enter some random character like 's' or '#' or something. If I input 's', it will say "You need to enter a digit!" twice.
I'm guessing that my loop statement is badly formatted. But I'm not sure what's wrong with it.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <ctype.h>
int main(){
int q = rand() % 10);
char g ='\0';
printf("I'm thinking of a number from 0-9. Guess what it is!\n");
LOOP:
scanf("%c", &g);
if (isdigit(g) && g == q){
printf("Wow, you got it right! Congratulations!\n");
}
else if (isdigit(g) && g != q){
printf("Oof, nice try. But try again!\n");
goto LOOP;}
else{
printf("You need to enter a digit!\n");
goto LOOP;
};
return 0;
}
isdigit returns true of g is the ascii representation of a number ie. it checks for ascii codes between 0x30 and 0x39. g is already a number so the isdigit call is not required. scanf reads from stdin and converts it to a number. You should change the %c to %d in scanf and check the scanf return code to ensure a valid number was read. You will also need to check the range of the input is that c is between 0 and 100.
Task:
Create a number guessing game where the user has a limited number of guesses to figure out what the randomly generated number is
Check whether the user has inputted a digit or character using "Isdigit" informing them to input a number between 1 and 20 if they use the wrong input or guess out of the expected range.
Using a while loop limits the user guesses
After the user runs out of guesses close the program
Problem I'm facing: I'm new to programming and so I don't have too much experience yet. It's my first time trying to understand the is digit function and I feel like there is a more efficient way of solving this problem.
Since I'm using 2 data types when trying to compare int's and chars I can't make a direct comparison but I figured out the difference between char 1 and int 1 is 48 apart so I made that as a temporary solution. But it only works for single-digit numbers
I've read that I might be able to go through the string character by character to make sure each of them are a digit before the input is accepted and combine the string at the end but I'm not sure how to do that
The user can't input more than 1 character or the program ends
I'd also like to fix any other bugs people may find and write the code in a more effective and understandable way
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main()
{
int iRandomNum = 5; //setting up a number as a placeholder until Code works
char guess; //char being used as I beleive it needs to be char for isdigit to function
int guessCount = 0; //
int guessLimit = 3;
int outOfGuess = 0;
srand(1-10);
//iRandomNum = (rand()%20)+1;
while (guess != iRandomNum && guessCount != 3 && outOfGuess == 0){ //Intended to break out of loop once any variable is satisfied
if(guessCount< guessLimit){
printf("\n%d", iRandomNum);
printf("\nYou have %d guesses left", guessLimit- guessCount); //extra user info
printf("\nGuess the number between 1 - 10: ");
scanf(" %s", &guess);
if (isdigit(guess)==0)
{
printf("\nEnter a digit!");
guessCount++; //supposed to limit user to 3 chances
}else
{ //need help solving this
printf("\nYou entered %d\n", guess - 48); //Using for testing
guess = guess - 48;
if (guess == iRandomNum) //I dont think functions as char and int are different data types
{
printf("\nYou've Won");
break;
}else{
printf("\nWrong guess");
guessCount++;
}
}
}else //Once user runs out of guesses while loop should break an then display following data
{
printf("Second else");
guessCount++;
//outOfGuess = 1;
}
}
if (outOfGuess == 1){
printf("\nOut of guesses!");
}
else{
printf("\nCongratulations!");
}
return 0;
}
An issue not already mentioned in comments: guess is used in the while condition before it has been assigned a value - that's an error.
Regarding the main problem:
In order to allow the user to input more than 1 character (i. e. up to two for a two-digit number), you can use a sufficiently sized character array. Of course you then have to account for a second character when checking using "Isdigit". So e. g. replace
scanf(" %s", &guess);
if (isdigit(guess)==0)
with
char s[2+1]; // +1 for string-terminating null character
if (scanf(" %2s", s) < 1 || !isdigit(s[0]) || s[1] && !isdigit(s[1]))
In order to convert the string in the array to an integer, you can simply use atoi:
guess = atoi(s);
I am relatively new to C, I have to do it for school unfortunately and I am having issues with it at the easiest exercises.
Here I have to check if a number is in a certain interval, for example between 4 and 6. I made it like this.
#include <stdio.h>
int main(){
int i;
printf("Value to check Interval \n");
scanf("%s", i);
if (i>4 && i<6){
printf("%s Value is in first interval\n", i);
}
}
The scanf to enter the number and check if it is in the interval. But even if I enter a number that is part of it, for example 5, the printf doesn't do anything. I tried also to add an else statement for numbers outside the interval, but also there the printf did not change anything.
It is because you have declared i variable as int and you are taking input as string so when it is checking condition it is getting null value in i variable and not able to enter if block check below code
#include <stdio.h>
int main(){
int i;
printf("Value to check Interval \n");
scanf("%d",&i);
if (i>4 && i<6){
printf("%d Value is in first interval\n", i);
}
}
try compiling your code without if condition i variable will return a null value
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void){
int corX = 0;
do{
printf("Please enter number X:\n");
scanf("%d",&corX);
} while(!(isdigit(corX) && corX>1 && corX<80));
printf("You entered X as: %d\n",corX);
return 0;
}
Hi! The code above should check if the entered value is an integer and fit to the range. If not, program should ask again. Unfortunately, it does not work in this way. Whatever I write, loop always go through and in a result I receive entered number for numbers and 0 for other signs. Could somebody explain, what I am doing wrong?
there seems to be a problem in your while condition. I rewrote it and I get what I think is the behavior you wanted (ask for input when input smaller 1 or greater 80)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int clean_stdin()
{
while (getchar()!='\n');
return 1;
}
int main(void){
int corX = 0;
do{
printf("Please enter number X:\n");
scanf("%d",&corX);
} while( ( corX<1 || corX>80 ) && clean_stdin() );
printf("You entered X as: %d\n",corX);
return 0;
}
edit: I did not check my initial post careful enough. The checking for isdigit is not needed at all as you already are using %d in scanf, I removed it completely from the while condition. As quick fix for the infinite loop problem I added the clean_stdin() function that is mentioned in the accepted answer of this post How to scanf only integer and repeat reading if the user enter non numeric characters? that #Gangadhar mentioned in his comment and which I recommend for reading (which also I should have done before posting)
So I was coding this program and after I was done, I tried to run it but for some reason nothing shows up on the console. I went through the code multiple times and tried multiple ways of performing the same function, which is basically to keep on getting inputs from the user until he/she enters 0, then display the largest and second largest number, and if the user enters 0 and there are no numbers available then continue checking. I think may be there is an infinite loop or some other problem with it. Here is the code:
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
void main()
{
int input,z;
int large,small,counter=0;
bool a=false;
while (1){
if(scanf("%d\n",&input)>0)
{
small=input;
counter++;
if(small>large)
{
z=small;
small=large;
large=z;
}
}
else if(scanf("%d\n",&input)<0)
{
printf("Please enter a positive value\n");
}
else if(scanf("%d\n",&input)==0)
{
if(small>0 && large>0)
{
printf("There are in total %d positive integers entered",counter);
printf("The largest number is %d, while the second largest is %d", large,small);
a=true;
break;
}
else
{
printf("You have to enter atleast two positive integers");
}
}
}
}
Any sort of help would be appreciated, thank you.
The scanf function doesn't return the input, it returns how many numbers it read.
Since your code reads numbers one at a time, scanf will always return 1, causing an infinite loop.
To fix this, hoist the scanf call outside the branching code:
while (1) {
scanf("%d", &input);
if (input > 0) ...
else if (input < 0) ...
else ...
}
There are more bugs in your code (Rohan pointed out one of them) but this should solve the black screen.
Each time you check the value entered, you're doing another scanf() or trying to read a new value instead of checking the value of the number that was entered. And the value you're checking is the return value of scanf(), but the number that's entered is actually stored in your "input" variable. So yes, there are a few things going on here, but you're essentially in an infinite loop because the entered values aren't getting read or evaluated properly.
The C function scanf() doesn't take a newline. Instead use:
scanf("%d", &input);
Also, initialize your "large" variable to 0 when you define it (it's value is not 0 and will give you unpredictable results):
int large = 0, small, counter = 0;
What you want to do is ONLY one scanf() at the top of your while loop to read in a number. After that, your if's should be testing the value of "input":
while (1)
{
scanf("%d", &input);
if (input > 0) /* positive number entered */
{
/* do something */
} else if (input < 0) /* negative number entered */
{
/* print error */
} else /* no need to test value since it must be 0 at this point */
/* do stuff */
}
}
Happy C coding! ;-)
If you walk carefully through the logic of your program, you'll see it doesn't make sense. For example, if a number is entered, you never print anything.