How to print ASCII value of 2 characters? - c

I'm trying to print ASCII value of "\t" i.e escape sequence.
But my program only prints the ASCII value of "\" i.e ASCII value will be 92.
Is there any way to print ASCII value of 2 characters ?
Help would be really appreciated.I have included my code below.
#include<stdio.h>
main()
{
char b=0;
printf("Enter any character to print it's ASCII value : ");
scanf("%c",&b);
printf("The ASCII value of '%c' is %d",b,b);
return 0;
}

Capture input of backslash and handle it as a separate input. A switch can be used to print the result for the escaped characters.
#include <stdio.h>
int main( void) {
char b=0;
printf("Enter any character to print it's ASCII value : ");
if ( 1 == scanf(" %c",&b)) {
if ( b == '\\') {//read a backslash
if ( 1 == scanf(" %c",&b)) {
switch ( b) {
case 't' :
printf("The ASCII value of '\\t' is %d\n", '\t');
break;
case '\\' :
printf("The ASCII value of '\\' is %d\n", '\\');
break;
default :
printf ( "not handled yet\n");
}
}
}
else {
printf("The ASCII value of '%c' is %d\n",b,b);
}
}
return 0;
}
Output
Enter any character to print it's ASCII value : \t
The ASCII value of '\t' is 9
Enter any character to print it's ASCII value : \\
The ASCII value of '\' is 92
To get the code for a backslash, two backslashes must be entered

This code might help you understand what is going on here:
#include <stdio.h>
const char* escaped(int ch) {
switch (ch) {
case '\t': return "tab";
case '\n': return "newline";
case '\r': return "carriage return";
// continue with other escaped characters
default: return "not escaped";
}
}
int main()
{
char b = 0;
printf("Enter any character to print it's ASCII value : ");
scanf("%c", &b);
printf("The ASCII value of '%c' is %d and is also known as: %s\n", b, b, escaped(b));
}
Just to be really clear, for a tab, at the keyboard you just press the tab key. You do not enter the string "\t". The string "\t" will be interpreted as 2 characters: '\' and 't'.
The \ escape code is something you would use in writing strings in your C code.
For example, if you type the string "trying" into some C source code, then you are entering the stream of characters: t r y i n g but if you type the string: "\trying" then the first character is indicating that this is an escaped character and is a convenient way to indicate that you really wanted a tab followed by the characters: r y i n g.
With the above code, if you enter "\t" scanf is only getting from stdin, one character at a time, so it just takes the first character, the backslash (start of an escape sequence), and will print out:
Enter any character to print it's ASCII value : \t
The ASCII value of '\' is 92 and is also known as: not escaped
the 't' character is still in the input stream and the program has not handled this character.
scanf does not interpret "\t" as a tab but as the character stream \ followed by t. That is causing your confusion.
You will experience some problems in running this code. For example, you want to try backspace, which is \b or decimal 8 value. scanf will probably ignore it and assume you are attempting to backspace a previous character. But for other escaped characters such as tab character and newline it will work.
Have a read of this: https://en.wikipedia.org/wiki/Escape_character

#define INV (EOF -1)
int z = 0, tmp = INV;
char buff[6] = "\\0";
while (1)
{
if (tmp == INV)
z = getchar();
else
{
z = tmp;
tmp = INV;
}
if (z == EOF || tmp == EOF) break;
if (z == '\\')
{
tmp = getchar();
switch (tmp)
{
case 't':
z = '\t';
tmp = INV;
break;
case 'b':
z = '\b';
tmp = INV;
break;
case 'r':
z = '\r';
tmp = INV;
break;
case 'n':
z = '\n';
tmp = INV;
break;
// add here anothere ones
default:
break;
}
}
printf("Char \\0%03o - '%c'\t\t has the ascii code of %03d decimal 0x%02X hexadecimal\n", z, z < 32 ? ' ' : z, z, z);
}

Related

How to check if all the upper-case letters are present in the input the user gives?

I'm trying to check if all the upper-case letters are present in the input the user entered.
I tried to make an array of 26 values, 0 will represent A and 25 is Z. At first I initialize the values to 0.
After that I asked the user for input and then I checked if it matches with the ASCII. If yes, I changed the array value to 1.
After that, I make sure all the array values are 1; if yes all the letters were in the input.
I assume that the user will end the input with 0.
The input is "THE Q$#UICK BROWN FOX JUMPS OVER tHe LAZY DOG!0".
This is the code:
#include <stdio.h>
int main()
{
int z;
int x = 1;
int arr[26] = {0};
printf("enter a sentance to check if all latter in ABC are in the sentance (in upper case):\n");
while (x!=0) {
scanf(" %d", &x);
z = x - 65;
if (z>=0 && z<=25) {
arr[z]=1;
}
}
z=0;
while (arr[z]==1 && z<26) {
++z;
if (z==26) {
printf("all the ABC in ur sentance\n");
break;
}
}
printf("all the ABC does not in ur sentance\n");
return 0;
}
There is no output and I think it's because there is a problem with the scanf, but I don't know how to solve it.
%d format specifier in scanf() is for reading integers, not characters. In this case, you should use getchar() instead of scanf() to read characters one-by-one.
The character 0 don't have the value 0. (it is 48 in ASCII).
Using magic numbers like 65 is not good. Using character constants like 'A' should be good in this case to make the meaning clear.
The part
while (x!=0) {
scanf(" %d", &x);
z = x - 65;
if (z>=0 && z<=25) {
arr[z]=1;
}
}
should be:
while ((x = getchar()) != '0' && x != EOF) {
z = x - 'A';
if (z>=0 && z<=25) {
arr[z]=1;
}
}
Also note that "all the ABC does not in ur sentance\n" will be printed even after "all the ABC in ur sentance\n" is printed. You should use return 0; instead of break; to finish the execution of the function and prevent the extra string from being outputted.
You need to use %c to read a character and convert it to its character code. %d reads the representation of an integer.
If the character 0 ends the input, you need to compare with '0', not 0.
You can use isupper() to test if a character is an uppercase letter, rather than testing the range yourself.
The loop to check that all the characters have been entered can be simplified as I've shown below.
#include <stdio.h>
#include <ctype.h>
int main()
{
int z;
char x;
int arr[26] = {0};
printf("enter a sentance to check if all latter in ABC are in the sentance (in upper case):\n");
while (1) {
scanf(" %c", &x);
if (x == '0') {
break;
}
if (isupper(x)) {
z = x - 'A';
arr[z]=1;
}
}
for (z = 0; z < 26; z++) {
if (arr[z] == 0) {
printf("all the ABC are not in your sentance\n");
return 0;
}
}
printf("all the ABC in your sentance\n");
return 0;
}

Changing the case of a character

I want to keep entering a character till a '*' is entered and change the case of the character. The code I have written is
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
char character;
char con_char;
while(1)
{
printf("Enter a character:");
scanf("%c",&character);
printf("ASCII value of %c is %d\n", character, character);
if (character=='*')
{
printf("The program terminates\n");
exit(0);
}
else if (character>='a' && character<='z')
{
con_char = toupper(character);
printf("%c\t\t%c\n", character, con_char);
}
else if (character>='A' && character<='Z')
{
con_char = tolower(character);
printf("%c\t\t%c\n", character, con_char);
}
else
{
con_char=character;
printf("%c\t\t%c\n", character, con_char);
}
}
return 0;
}
The program works well but only for the format of the output. The line "Enter a character" is displayed in the output two times for a single input. I am not able to understand the reason. Please help.
Output:
Enter a character:f
ASCII value of f is 102
f F
Enter a character:ASCII value of
is 10
Enter a character:

Using c code to make a caesar cipher?

Hello good people of the stack overflow.
Explanation
I am trying to to the following.
My program needs to take a stream of letters as the input and then for the output rotate 13 paces forward.
For example
A becomes N
B becomes O
C becomes P
D becomes Q
and so on
For this program I need to use the ascii table. So for example lower case a=97 once my program is done it becomes n=110
I wrote a little formula for this
c=(c+13-97)% 26+97 where c is my letter. as you can see if c=97 then c will end up being 110.
So here is my program
As it is seen I used an if statment to determine if I have a capital or lower case letter.
/* 97 is lower case a in ascii and 122 is lower case z*/
# include <stdio.h>
int main() {
char c;
printf("please enter a character:");
while (c!=-1) {
c=getchar();
putchar (c);
if ( c>=97 && c<=122) {
c=(c+13-97)% 26+97 ;
printf("%c \n " ,c);
}
else
c=(c+13-65) % 26 +65 ;
printf("%c \n " ,c);
}
return 0;
}
My problem is with the output for example if I plug in a
instead of n I get
an
n
1
Your code is absolutely fine with some minor changes in it.
/* 97 is lower case a in ascii and 122 is lower case z*/
# include <stdio.h>
int main()
{
char c;
printf("please enter a character:");
while (c!=-1)
{
c=getchar();
//putchar (c); // Avoid Printing entered character
if ( c>=97 && c<=122)
{
c=((c+13-97)% 26)+97 ;
printf("%c \n " ,c);
}
else
{ // Braces missing
c=((c+13-65) % 26) +65 ;
printf("%c \n " ,c);
}
return 0;
}
}
Output :
please enter a character : a
n
One other issue that you will run into is the need to flush the \n remaining in the input buffer before reading the next character. Basically, what occurs is after a character is entered and the user presses Enter, c is read from the input buffer, but '\n' remains. So the next time the loop is entered \n is already present in the input buffer and is taken as c for that iteration.
To prevent this from occurring, the easiest way to flush the input buffer is to declare a throw-away int say int flush and following each read of a character, add the following:
do { flush=getchar(); } while (flush != '\n');
This will extract all remaining characters from the input buffer preparing it for the next read. (Note: fflush does not do this for input streams) An implementation with this incorporated is:
#include <stdio.h>
int main () {
int c = 0; /* Always initialize variables */
int flush = 0;
int new = 0;
printf ("\nPlease enter a character (ctrl+d to exit):\n\n");
while (printf (" char: ") && (c = getchar()) != -1) {
do { flush=getchar(); } while (flush != '\n'); /* flush input buffer */
if (c >= 'a' && c <= 'z')
{
new = (c + 13 - 97) % 26 + 97;
printf ("\t lower-case '%c' becomes: '%c'\n\n", c, new);
}
else if (c >= 'A' && c <= 'Z')
{
new = (c + 13 - 65) % 26 + 65;
printf ("\t upper-case '%c' becomes: '%c'\n\n", c, new);
}
else
{
printf ("\n invalid character, try again\n\n");
}
}
printf ("\n\nexiting.\n\n");
return 0;
}
output:
Please enter a character (ctrl+d to exit):
char: a
lower-case 'a' becomes: 'n'
char: b
lower-case 'b' becomes: 'o'
char: n
lower-case 'n' becomes: 'a'
char: o
lower-case 'o' becomes: 'b'
char: A
upper-case 'A' becomes: 'N'
char: B
upper-case 'B' becomes: 'O'
char: N
upper-case 'N' becomes: 'A'
char: O
upper-case 'O' becomes: 'B'
char:
exiting.
Good luck with your project. Drop a comment if you run into additional problems.
Multiple Character Version Using getline
Regarding your question about line input. Here is a version using getline to read multiple characters from stdin:
#include <stdio.h>
int main () {
int new = 0;
ssize_t nread = 0; /* number of chars read by getline */
char *line = NULL; /* string holding chars - getline allocates when NULL */
size_t n = 0; /* limit number of bytes to (ignored when 0) */
char *p = NULL; /* point to use to iterate over each char in line */
int index = 0; /* simple index for formatted output. */
printf ("\nPlease enter characters to translate (ctrl+d to exit):\n");
while (printf ("\n input: ") && (nread = getline (&line, &n, stdin) != -1)) {
index = 0; /* reset index */
p = line; /* assign pointer to line */
printf ("\n"); /* just because it looks nice */
while (*p != '\n') /* getline consumes the '\n' */
{
if (*p >= 'a' && *p <= 'z')
{
new = (*p + 13 - 97) % 26 + 97;
printf ("\t char[%2d] : %c => %c\n", index, *p, new);
}
else if (*p >= 'A' && *p <= 'Z')
{
new = (*p + 13 - 65) % 26 + 65;
printf ("\t char[%2d] : %c => %c\n", index, *p, new);
}
else
{
printf ("\n char[%2d] : %c => invalid character\n", index, *p);
}
p++;
index++;
}
}
printf ("\n\nexiting.\n\n");
return 0;
}
output:
Please enter characters to translate (ctrl+d to exit):
input: aAbBcCmMnNoO
char[ 0] : a => n
char[ 1] : A => N
char[ 2] : b => o
char[ 3] : B => O
char[ 4] : c => p
char[ 5] : C => P
char[ 6] : m => z
char[ 7] : M => Z
char[ 8] : n => a
char[ 9] : N => A
char[10] : o => b
char[11] : O => B
input:
exiting.
The while loop should be
while ((c=getchar()) != EOF)
Your code is checking the value of c before c is initialized. You should have gotten a warning about that.
You should not be using hard-coded ASCII values in your code. Lower case a is 'a'. Lower case z is 'z'. So, for example, you can write
if ( c >= 'a' && c <= 'z' )
Note that stdin buffers characters until you press the return key. When you do press the return key, getchar will give you the character that you typed followed by a newline '\n' character. Your code only handles lower case and upper case characters. You need to modify the code to handle non-alpha characters correctly, e.g. spaces, punctuation, newlines.

How to get a character ASCII value in a integer variable?

I'm new in C and I couldnt find the answer to my question in the forum.
The point is, I need to get a value of deck cards from the user. So it can spread from 2 to 10 and also be 'J', 'Q', 'K' or 'A'. That means it can be a integer or a character.
I'm trying to put it in an integer variable called "_val1". This work for any number from 0 to 10. I expected that if I typed a letter, _val1 would get the ASCII value of that character (wich I could use later for my pourposes). But instead _val1 geta value '0' and the letter is automatically passed to my next variable call (wich is _naipe1).
How can I solve that?
That means, how cam I use scanf to get either a integer value or the ASCII value of a character?
short int _val1, _val2;
char _naipe1, _naipe2;
printf("Qual a 1ª carta?\n Valor:");
scanf(" %hd", &_val1);
printf("Valor 1 = %hd \n", _val1 );
printf(" Naipe:");
scanf(" %c", &_naipe1);
well, if I were you I'd try to simplify the problem:
get the ASCII value of the card representation from '2' to '9' and 'J','Q','K','A' ; there you can simply use a scanf("%c") or even better a getchar() operation.
then either you keep using the ASCII representation of your cards throughout your algorithm, or you can translate it using a mapping function such as:
int map(char card) {
switch (card) {
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return card-'0';
case 'A':
return 1;
case 'J':
return 10;
case 'Q':
return 11;
case 'K':
return 12;
}
}
First, there are 52 cards to a typical poker deck, These are split into 4 suits: hearts, diamonds, spades and clubs. This kind of suggests that user input will be something like: 10s, Ad, 3c, etc (meaning 10 of spades, Ace of diamonds and 3 of clubs) So, not only must you determine the value of the individual card, you also must determine the suit.
This will not solve all of those requirements, but it will at least answer your most direct question, how to read an int or a char using scanf().
This will demonstrate that:
#include <stdio.h>
int main(int argc, char** argv)
{
int aNumber;
char aChar;
printf("\nEnter a number:");
scanf("%d", &aNumber);
printf("\nEnter a character:");
scanf("%c", &aChar);
printf("\nThe number entered is %d\n", aNumber);
printf("\nThe character entered is %c\n", aChar);
return 0;
}
You can also simply have all the values in a string such as
char cards[]={"Ad Js 10c 2c Qh"};
Then parse it using strtok(), then test each token for its ascii content, using functions like isdigit() or isalpha()
Note: you will have to map each card to a value to keep them straight, something like this abbreviated enum may work:
enum {
AD = 1, //start enum values at 1 for the diamonds suit
2D,
3D,
...//fill in rest of cards here
JC,
QC,
KC, // last card == 52, with the clubs suit
};
The reason your output from _val1 is 0 when entering a letter lies in the fact that you've declared _val1 as an short int. You should be using a char. Then you can assign and compare their ascii values.
char card;
int value;
scanf("%c", card);
if(card < 58 && card > 49)
value = card - 48;
else {
switch(card) {
case 'a': value = 1;
case '0': value = 10;
case 'j': value = 11;
case 'q': value = 12;
case 'k': value = 13;
default: printf("Must enter 0-9 (0 for 10 card), or a, j, q, k\n");
}
}
To read in "A", "2", "3", ... "10", "J",... "K", use fgetc() and strchr().
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
short GetCardRank(void) {
static const char rank[] = "A234567891JQK";
short val = -1;
int ch = fgetc(stdin);
while (isspace(ch)) ch = fgetc(stdin); // Skip leading white-space
char *p = strchr(rank, toupper(ch)); // Use toupper() to make case insensitive
if (ch != EOF && p != NULL && *p != '\0') {
short val = (short) (p - rank + 1);
if (val != 10) return val;
ch = fgetc(stdin);
if (ch == '0') return val;
val = 1; // Allow a lone '1' to act like an 'A'
}
ungetc(ch, stdin); // Put back unused char for next IO function
return val;
}
I'm trying to put it in an integer variable called "_val1". This work for any number from 0 to 10. I expected that if I typed a letter, _val1 would get the ASCII value of that character (wich I could use later for my pourposes). But instead _val1 geta value '0' and the letter is automatically passed to my next variable call (wich is _naipe1)
The problem is that the %d conversion specifier only recognizes strings of decimal digits (with an optional leading + or -) and will stop reading at the first non-digit character; if you type in something other than a digit, then the input operation will fail and that character will be left in the input stream.
Your best bet is to read your input as text, then convert it to a numerical value manually, something like the following:
#include <ctype.h>
#include <stdlib.h>
/**
* Reads a card's face value (2-10,J,Q,K,A) from standard input
* Returns 0 on error
*/
short get_card_value( void )
{
char buf[4]; // large enough to hold a 2-digit string plus newline plus 0 terminator
short val = 0;
if ( fgets( buf, sizeof buf, stdin ) != NULL )
{
char *chk;
short tmp = (short) strtol( buf, &chk, 0 );
if ( isspace( *chk ) || *chk == 0 )
{
if ( tmp >= 2 && tmp <= 10 )
val = tmp;
}
else
{
switch( tolower( *chk ) )
{
case 'j': val = 11; break;
case 'q': val = 12; break;
case 'k': val = 13; break;
case 'a': val = 11; break;
default: break;
}
}
}
// else read error
return val;
}
You'd call this as
val1 = get_card_value();
if ( val1 == 0 )
// error on input
This code doesn't do any length checking on input, so if you enter a card value of 1234567890, that won't be handled gracefully.
Don't use leading underscores in your variable names; names with leading underscores are reserved for the implementation.

Accented/umlauted characters in C?

I'm just learning about C and got an assignment where we have to translate plain text into morse code and back. (I am mostly familiar with Java so bear with me on the terms I use).
To do this, I have an array with the strings for all letters.
char *letters[] = {
".- ", "-... ", "-.-. ", "-.. ", ".", "..-." etc
I wrote a function for returning the position of the desired letter.
int letter_nr(unsigned char c)
{
return c-97;
}
This is working, but the assignment specifications require the handling of the Swedish umlauted letters åäö. The Swedish alphabet is the same as the English with these three letters in the end. I tried checking for these, like so:
int letter_nr(unsigned char c)
{
if (c == 'å')
return 26;
if (c == 'ä')
return 27;
if (c == 'ö')
return 28;
return c-97;
}
Unfortunately, when I tried testing this function, I get the same value for all of these three: 98. Here is my main, testing function:
int main()
{
unsigned char letter;
while(1)
{
printf("Type a letter to get its position: ");
scanf("%c", &letter);
printf("%d\n", letter_nr(letter));
}
return 0;
}
What can I do to resolve this?
The encoding of character constants actually depend on your locale settings.
The safest bet is to use wide characters, and the corresponding functions. You declare the alphabet as const wchar_t* alphabet = L"abcdefghijklmnopqrstuvwxyzäöå", and the individual characters as L'ö';
This small example program works for me (also on a UNIX console with UTF-8) - try it.
#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(int argc, char** argv)
{
wint_t letter = L'\0';
setlocale(LC_ALL, ""); /* Initialize locale, to get the correct conversion to/from wchars */
while(1)
{
if(!letter)
printf("Type a letter to get its position: ");
letter = fgetwc(stdin);
if(letter == WEOF) {
putchar('\n');
return 0;
} else if(letter == L'\n' || letter == L'\r') {
letter = L'\0'; /* skip newlines - and print the instruction again*/
} else {
printf("%d\n", letter); /* print the character value, and don't print the instruction again */
}
}
return 0;
}
Example session:
Type a letter to get its position: a
97
Type a letter to get its position: A
65
Type a letter to get its position: Ö
214
Type a letter to get its position: ö
246
Type a letter to get its position: Å
197
Type a letter to get its position: <^D>
I understand that on Windows, this does not work with characters outside the Unicode BMP, but that's not an issue here.
In general encoding stuff is quite complicated. On the other hand if you just want a dirty solution specific to your compiler/platform than add something like this to your code:
printf("letter 0x%x is number %d\n", letter, letter_nr(letter));
It will give hex value for your umlauts. Than just replace in if statements your letter with number.
EDIT You say that you are always getting 98 so your scanf got 98 + 97 = 195 = 0x3C from console. According to this table 0x3C is start of UTF8 sequence for common LATIN SMALL LETTER N WITH Something in Latin1 block. You are on Mac OS X ?
EDIT This is my final call. Quite hackery but it works for me :)
#include <stdio.h>
// scanf for for letter. Return position in Morse Table.
// Recognises UTF8 for swedish letters.
int letter_nr()
{
unsigned char letter;
// scan for the first time,
scanf("%c", &letter);
if(0xC3 == letter)
{
// we scanf again since this is UTF8 and two byte encoded character will come
scanf("%c", &letter);
//LATIN SMALL LETTER A WITH RING ABOVE = å
if(0xA5 == letter)
return 26;
//LATIN SMALL LETTER A WITH DIAERESIS = ä
if(0xA4 == letter)
return 27;
// LATIN SMALL LETTER O WITH DIAERESIS = ö
if(0xB6 == letter)
return 28;
printf("Unknown letter. 0x%x. ", letter);
return -1;
}
// is seems to be regular ASCII
return letter - 97;
} // letter_nr
int main()
{
while(1)
{
printf("Type a letter to get its position: ");
int val = letter_nr();
if(-1 != val)
printf("Morse code is %d.\n", val);
else
printf("Unknown Morse code.\n");
// strip remaining new line
unsigned char new_line;
scanf("%c", &new_line);
}
return 0;
}
Hmmm ... at first I'd say the "funny" characters are not chars. You cannot pass one of them to a function accepting a char argument and expect it to work.
Try this (add the remaining bits):
char buf[100];
printf("Enter a string with funny characters: ");
fflush(stdout);
fgets(buf, sizeof buf, stdin);
/* now print it, as if it was a sequence of `char`s */
char *p = buf;
while (*p) {
printf("The character '%c' has value %d\n", *p, *p);
p++;
}
Now try the same with wide characters: #include <wchar.h> and replace printf with wprintf, fgets with fgetws, etc ...

Resources