While loop go through irrespective of conditions in C - c

#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)

Related

Two mutually exclusive parts of an if...else if ....else statement in C are coming up. What am I missing?

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.

I can't show the time in output.Even when i typed true (Y or y)

#include <stdio.h>
#include <stdlib.h>
#define timeteller(choose) (choose == 'Y' || choose == 'y') ? __TIME__ :"ok we dont show time now .."
int main (){
int choose1;
printf("do u want to learn time ?...\n");
scanf(" %c",&choose1);
if (timeteller(choose1) ){
printf("%s",timeteller(choose1));
}
else {
printf("%s",timeteller(choose1));
}
return 0;
}
Here's a version that works and is a bit cleaner:
Macro name in full caps; common C code convention.
Let macro only check the user input.
Put macro parameter between ( ): (choose). Not needed here but it's a common convention to avoid issues with more complex expressions as argument.
Nice code formatting.
Printing newline to get nice program output.
BTW, it would probably have been better to use a function, instead of a macro. But that's a whole other subject.
The reason why it didn't work with int choose1; is that after you define it, choose1 contains 'random' bytes from the stack. Then your scanf() writes only one of these bytes to the entered character value, but the remaining bytes still contain stack garbage.
Just add printf("%d\n", choose1); before and after your scanf() and you'll see.
Because of this, in official terms your program results in 'undefined behaviour'. Your program could have worked if choose1 coincidently got the value 0 from the stack or if your compiler/platform was friendly and initialized it to 0.
#include <stdio.h>
#include <stdlib.h>
#define IS_Y(choose) ((choose) == 'Y' || (choose) == 'y')
int main()
{
char choose;
printf("do u want to learn time ?...\n");
scanf(" %c", &choose);
if (IS_Y(choose))
{
printf("%s", __TIME__);
}
else
{
printf("Ok, we don't show time now ...");
}
printf("\n");
return 0;
}

Value that scanf has read in not functioning as expected

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!

While loop with tables C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 30
int main()
{ char c, y, input[N];
int X, i=0, j;
printf("Give displacement\n");
scanf("%d",&X);
printf("Give chars\n");
while(((c=getchar()) !=EOF) && (i<N-1)){
input[i]=c;
i++;
}
input[i]='\0';
j=0;
for(j=0; j<=i-1; j++){
if (isalpha(input[j])){
if (isupper(input[j]))
y=(input[j]-'A'+X)%26+'A';
else
y=(input[j]-'a'+X)%26+'A';
putchar(y);
}
}
return 0;
}
hey all. well, this code doesnt seems to works as it should. It skips 2 positions at the table instead of one. Which makes the program unusable since i need a table of 30 positions. I think that the problem is in the while loop, but i really cant find it. Any help would be apprecieted.
Thanks in advance.
After the call to scanf, there's a newline left in the input buffer. That newline becomes the first character read by getchar.
To get the newline out of the buffer, add a separate call to getchar right after the scanf call:
scanf("%d",&X);
getchar();
That will give you the additional character you're missing.
Also, as mentioned in the comments, c should be defined as an int instead of a char, because getchar returns an int. Otherwise, the test for EOF will always be false.
if you want 30 characters you have to define N as 31
[0 - 29] + '\0'
In your first while loop i believe that the second test is wrong:
Use it like this:
while(((c=getchar()) !=EOF) && (i<=N-1)){
input[i]=c;
i++;
}

why doesn'y this code work?

This question is regarding the SPOJ tutorial problem :
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
I want to run the program without if -else statements but the program doesn't work. Can someone please tell me what am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
while (i != 42)
{
putchar(i);
i = getchar();
}
exit(0);
}
Here is a quick and dirty way of getting the result that you want.
Since you want the user to enter number (which is composed of multiple characters), you will want to use scanf() instead of getchar().
scanf() documentation : http://www.cplusplus.com/reference/cstdio/scanf/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
while (i != 42)
{
scanf("%d", &i);
printf("You have entered : %d\n", i);
}
printf("You have successfuly entered 42!\n");
exit(0);
}
Hope this helps.

Resources