ASCII value not giving correct letters - c

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

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.

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'.

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