why doesn'y this code work? - c

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.

Related

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;
}

Problems with array and scanf function working together

I am a beginner. I want to write a program, that will guess a number, which user picked. In general, user pick a number within the given limit, the program will generate a random number within same limit, ask user if it's a right number, Y/N answer, program reads it, then ask if user's number is bigger or smaller, reads the answer and pass this information to 2 additional functions.
(I didn't finish those yet, but the idea is that it will divide the rest of numbers in 2, ask again, bigger smaller, divide it once again by 2 and so on, till we get the answer.)
The problem is, that even if I use a simplest array of type char, I cannot get it work. The answer of the computer is if I didn't book enough memory for one of the arrays.
I'm still 2 chapters away from the arrays theme in my book, I just wanted to write this program. What I use here is what I've learned so far, so if it's possible, don't use any more complex functions and features of C in your answers.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int bigger(int number, int limit);
int lower(int number, int limit);
int main(void) {
system("COLOR B0");
const int Hlimit=100;
const int Llimit=0;
char alowwed_answer[]={'>','<'};
char answer[2];
char alowwed_answerYN[]={'Y', 'N'};
char answerYN[2];
srand((unsigned)time(NULL));
int numberTOguess;
printf("\r\nEnter your number from %i to %i, "
"and I will try to guess!: ",Llimit,Hlimit);
while(scanf("%i",&numberTOguess) )
{
int check=rand()%Hlimit;
printf("\r\nyour number is - %i Y/N?",check);
scanf("%c",&answerYN[0]);
printf("answer is %c\r\n", answerYN);//this line is for checking;
int check_answ=strcmp(answerYN[0],alowwed_answerYN[0]);
printf("check answer is %i",check_answ);//this line is for checking;
if(check_answ==0)
{
printf("I did it!");
break;
}
else if(strcmp(answerYN[0],alowwed_answerYN[1])==0)
{
printf("\r\nyour number is bigger '>' or smaller '<'?: ");
scanf("%c",&answer);
if(strcmp(answer[0],alowwed_answer[0])==0)
{
bigger(check, Hlimit);
}
else if(strcmp(answer[0],alowwed_answer[1])==0)
{
lower(check, Llimit);
}
}
}
printf("\r\nI did it!");
return 0;
}
int bigger(int number, int limit)
{
printf("it is bigger!");//I will finish this part as soon as I will get first part working.
return 0;
}
int lower(int number, int limit)
{
printf("it is lower!!!");//I will finish this part as soon as I will get first part working.
return 0;
}
Update
Thanks, I took your advice and change the statement type to SWITCH. But it still doesn't work properly. Somehow, nested switch doesn't function at all.
Look at the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int bigger(int number, int limit);
int lower(int number, int limit);
int main(void) {
system("COLOR B0");
const int Hlimit=100;
const int Llimit=0;
char answerBL;
char answerYN;
srand((unsigned)time(NULL));
int numberTOguess;
printf("\r\nEnter your number from %i to %i, "
"and I will try to guess!: ",Llimit,Hlimit);
while(scanf("%i",&numberTOguess) )
{
int check=rand()%Hlimit;
printf("\r\nyour number is - %i Y/N?",check);
scanf("%c",&answerYN);
switch(answerYN)
{
case 'Y':
printf("I did it!");
break;
case 'N':
printf("\r\nOk, your number is bigger '>' or smaller '<'?: ");
scanf("%c",&answerBL);
switch(answerBL)
{
case '>':
bigger(check, Hlimit);
break;
case'<':
lower(check, Llimit);
break;
}
default:
printf("Y or N?");
}
}
printf("\r\nEND!");
return 0;
}
int bigger(int number, int limit)
{
printf("it is bigger!");
return 0;
}
int lower(int number, int limit)
{
printf("it is lower!!!");
return 0;
}
Edit
Problem is solved, I found the reason and how to fix it. Here it is, from another topic
The basic problem is that scanf() leaves the newline after the number in the buffer, and then reads it with %c on the next pass. Actually, this is a good demonstration of why I don't use scanf(); I use a line reader (fgets(), for example) and sscanf(). It is easier to control.
You can probably rescue it by using " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.
But it will be easier in the long run to give up scanf() and fscanf() and use fgets() or equivalent plus sscanf(). All else apart, error reporting is much easier when you have the whole string to work with, not the driblets left behind by scanf() after it fails.
You should also, always, check that you get a value converted from scanf(). Input fails — routinely and horribly. Don't let it wreck your program because you didn't check.
answered Mar 5 '12 at 7:05
Jonathan Leffler
The function strcmp expected two pointers as arguments, pointers to the first characters of a null-terminated byte strings.
With e.g.
strcmp(answerYN[0],alowwed_answerYN[0]);
you have two major problems:
The array answerYN is (partially) uninitialized, its contents is (also partially) indeterminate. That means answerYN[1] is likely not the string terminator as needed.
alowwed_answerYN[0] is a single char not a pointer to a string. This should have given you a warning about invalid conversions or similar.
If you just want to compare characters, use normal comparison for equality ==, as in answerYN[0] == alowwed_answerYN[0].
Or why not skip alowwed_answerYN completely and plainly use the explicit character literal as in answerYN[0] == 'Y'. That's even clearer than using an array for the 'Y' and 'N'.

ASCII value not giving correct letters

I am a beginner.
I have written a program in c using eclipse. It does not give me any error and warnings while compiling and also not after executing it.
It prints out all ASCII values of all characters.
code
#include <stdlib.h>
#include <stdio.h>
int main(){
int a=0;
system("clear");
printf("\nthese are the ASCII values of characters given in front of them\n");
while(a<=255)
{
printf("%c %d \n",a,a);
a=a+1;
}
}
The output is strange, when I copy paste the output it disappears, thus this is link of the screen-shot of the output.
I can't take screen-shot of the whole screen, but after 126 the characters look like boxes. Is there something wrong in my code?
Many characters are unprintable, some are control codes for the terminal/console that enact actions such as clear screen, move the cursor, clear line... etc.
Use the isprint function defined in ctype.h to determine if the character is printable. A for loop would suit your requirements here better also, see below example.
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(){
system("clear");
printf("\nthese are the ASCII values of characters given in front of them\n");
int a;
for(a = 0; a <= 255; ++a)
{
printf("%c %d \n", isprint(a) ? a : '.', a);
}
}

Update previous line instead print new line

Here is a simple program in c. It take two integers and add them. In this code, I want to update previous line by new line instead making a new one, Can any body help me on this topic.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b;
printf("Enter two integer to add\r");
scanf("%d%d",&a,&b);
a=a+b;
printf("Your value is -- %d",a);
return 0;
}
I have use \r instead of \n, to take cursor back to the start. I have input data in program console which writing from start. But the next line "Your value is.." printed as new line, I want to remove the first line and then input value and print next line "Your value..". How do I do that? Please help me
You cannot move up in the terminal like that, unless using some complex lib as curses.
You can use the "clear screen" trick, maybe that would achieve what you want.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b;
system("clear"); // or "cls" on windows
printf("Enter two integer to add\r");
scanf("%d%d",&a,&b);
system("clear"); // or "cls" on windows
a=a+b;
printf("Your value is -- %d",a);
return 0;
}

While loop go through irrespective of conditions in 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)

Resources