Even though the char data type is an integer (and thus follows all of the normal integer rules), we typically work with chars in a different way than normal integers. Characters can hold either a small number, or a letter from the ASCII character set. ASCII stands for American Standard Code for Information Interchange, and it defines a mapping between the keys on an American keyboard and a number between 1 and 127 (called a code). For instance, the character ‘a’ is mapped to code 97. ‘b’ is code 98. Characters are always placed between single quotes.
The following two assignments do the same thing:
char chValue = 'a'; char chValue2 = 97;
cout outputs char type variables as characters instead of numbers.
The following snippet outputs ‘a’ rather than 97:
char chChar = 97; // assign char with ASCII code 97 cout << chChar; // will output 'a'
If we want to print a char as a number instead of a character, we have to tell cout to print the char as if it were an integer. We do this by using a cast to have the compiler convert the char into an int before it is sent to cout:
char chChar = 97; cout << (int)chChar; // will output 97, not 'a'
The (int) cast tells the compiler to convert chChar into an int, and cout prints ints as their actual values. We will talk more about casting in a few lessons.
The following program asks the user to input a character, then prints out both the character and it’s ASCII code:
#include "iostream";
int main()
{
using namespace std;
char chChar;
cout << "Input a keyboard character: ";
cin >> chChar;
cout << chChar << " has ASCII code " << (int)chChar << endl;
}
Note that even though cin will let you enter multiple characters, chChar will only hold 1 character. Consequently, only the first character is used.
One word of caution: be careful not to mix up character (keyboard) numbers with actual numbers. The following two assignments are not the same
char chValue = '5'; // assigns 53 (ASCII code for '5') char chValue2 = 5; // assigns 5
Escape sequences
C and C++ have some characters that have special meaning. These characters are called escape sequences. An escape sequence starts with a \, and then a following letter or number.
The most common escape sequence is ‘\n’, which can be used to embed a newline in a string of text:
#include <iostream>
int main()
{
using namespace std;
cout << "First line\nSecond line" << endl;
return 0;
}
This outputs:
First line Second line
Another commonly used escape sequence is ‘\t’, which embeds a tab:
#include <iostream>
int main()
{
using namespace std;
cout << "First part\tSecond part";
}
Which outputs:
First part Second part
Three other notable escape sequences are:
\’, which prints a single quote
\”, which prints a double quote
\\, which prints a backslash
Here’s a table of all of the escape sequences:
| Name | Symbol | Meaning |
|---|---|---|
| Alert | \a | Makes an alert, such as a beep |
| Backspace | \b | Moves the cursor back one space |
| Formfeed | \f | Moves the cursor to next logical page |
| Newline | \n | Moves cursor to next line |
| Carriage return | \r | Moves cursor to beginning of line |
| Horizontal tab | \t | Prints a horizontal tab |
| Vertical tab | \v | Prints a vertical tab |
| Single quote | \’ | Prints a single quote |
| Double quote | \” | Prints a double quote |
| Backslash | \\ | Prints a backslash |
| Question mark | \? | Prints a question mark |
| Octal/hex number | \(number) | Translates into char represented by octal/hex number |
2.8 — Constants
|
Index
|
2.6 — Boolean Values
|
2.8 — Constants
Index
2.6 — Boolean Values
[ Question answered in the forum. -Alex ]
Alex:
Ref.: cout << “First line\\nSecond line” << endl;
Why the second ‘\’ for ‘\n’ ?
Thanks,
Æ’ree
It was a typo. It’s fixed now. Thanks for noticing!
[...] 2007 Prev/Next Posts « 2.7 — Chars | Home | 2.9 — Hungarian Notation » Saturday, June 9th, 2007 at 10:43 [...]
[...] 2007 Prev/Next Posts « Break Time — Dice Wars | Home | 2.7 — Chars » Saturday, June 9th, 2007 at 3:34 [...]
Does that also apply to this?
cout << “First part\\tSecond part”;
Thanks for a great tutorial
Yup, that tab too. :) Thanks for noticing.
I made a program that makes a ASCII chart. Even though you can find this chart in almost any place dealing with coding. I thought it be fun to make my own reference.
Code
#include "stdafx.h"
#include <iostream>
int main()
{
using namespace std;
for(unsigned char nCount = 1; nCount <= 127; nCount++)
{
if (nCount <= 127)
cout << (int)nCount << " : " << nCount << endl;
}
return 0;
}
Oh! you may notice that nCount should be ucCount…thats because when I first wrote the program, it was an exercise that just counted up from 0. I just changed the int integer(int) to a char integer (unsigned char). Leaving the variable the same. Technicality there nothing wrong with that. However if you copy this program. I would suggest trying to use Hungarian Notion the correct way.
I wrote another ASCII table program based on your idea. It’s more complicated, and the character to begin with and the number of columns can be set during runtime.
For anyone who want to have a look, they’re all on my Windows Live Skydrive:
Source code
Executable
Thanks for your idea!
Hi Jeffey. Nice idea to construct such a code. Actually you don’t need to use the hypothetical statement if. I simplified your code:
#include<iostream> using namespace std; int main() { unsigned char chValue; for(chValue=1;chValue<128;chValue++) { cout<<int(chValue)<<":\t"<<chValue<<endl; } return 0; }thank you
Why do you need ‘/?’…. we can use question mark with cout….
Honestly, I don’t know. :)
Ok, i tried the /v for form feed, which in my case could be represented as a new page(would feed lines until the text shown would be gone. But instead it read out as the male gender sign as a character. I just dont want to have to input like 15 /n’s to make the same effect. I know an alternative is to make 15 /n’s a char constant and just input it when i need a new page but im just wondering if im just doing something wrong. Help, please! :P
I’ve never tried using the form feed char. I doubt it works on a monitor, though it might still work in printers… maybe.
You can’t stick 15 /n’s in a char because a char only holds one character, not 15. If you want 15 spaces, for now you’ll have to do 15
cout << "\n";until you learn how to do loops.I was just reading through the comments on this excellent tutorial.
If you want to wipe the text off the terminal you can use the clear screen command, system(“cls”)
#include <iostream> int main () { using namespace std; //Text too clear cout << "Hello World!" << endl; system("pause"); //Clear the Screen system("cls"); //Another pause cout << "Its gone!" << endl; system("pause"); return 0; }Hope This is what you were lookign for! :)
I tried declaring a variable as
but it didn’t work, how can i create a string variable
See http://www.learncpp.com/cpp-tutorial/66-c-style-strings/
iam using dev-c++
i cant get the correct output from this program…
it does not prints wrong or good…can u tell me why…
#include<iostream> using namespace std; int main() { int a; cout<<"input a number "; cin>>a; if(a==5) cout<<"good "; else cout<<"a wrong"; cin.get(); }First off, I think you should ask this in the forum, not here.
As for the code, I think it should print what you want, but maybe the output ends up appended to the first line (“input a number”) because you have not broken that line with an endl. The code itself seems fine…but you should work on your style a little! It is always good to indent to make code more readable :)
Keep coding. Use it for good.
Hi. Been having fun going through this tutorial. I was just compiling the ASCII code…
#include "iostream"; int main() { using namespace std; char chChar; cout << "Input a keyboard character: "; cin >> chChar; cout << chChar << " has ASCII code " << (int)chChar << endl; }It gave me a warning with visual c++ 2008 express until I changed the top line to…
Thanks for creating this tutorial! :)
Hey alex how come you have used #include “iostream”; (in the 4th coding)
i thought u said the “;” is not required
p.s. so far i love this tutorial very informative and most of all very easy to understand =)
Thanks a lot for this wonderful site and wish u guys all the best
respected ALEX, i have been deligently and sincerely trying to follow your “lessons”.
i tried to compile one code re. CHAR.
I AM NOT GETTING THE RESULTS AS PROJECTED BY U.
[One word of caution: be careful not to mix up character (keyboard) numbers with actual numbers. The following two assignments are not the same
view sourceprint?
1.
char chValue = '5'; // assigns 53 (ASCII code for '5')
2.
char chValue2 = 5; // assigns 5 ]
What ‘cout’ gives me is
a)5 for chValue
b)a sign like “club in playing cards”
please advise me—thanks prabhakar
the comments by me as on 2009-12-03 produced above be please be used in FORUM for begginers. i have registered 0n 2009-12-09. thanks prabhakar
i have the necessary message informing re. the registration but the link presribed is not working pl. advise prabhakar
link gives is
http://www.dev-spot.com/forums/index.php?action=activate;u=658;code=5d7dfff065
I have a bit of code that aims to print all the available codes and characters in a list,
#include <iostream> char eachChar=0; int main() {using namespace std; if (eachChar=127) return 0; else cout<<"Code "<<(int)eachChar<<" is "<<eachChar<<endl; eachChar=eachChar+1; main(); }Why isn’t this working as intended? There are no debug errors, but it seems to simply go strait to the “return 0;”, but returns a ridiculously large negative number, this
in red, to be specific. (still working with Code Blocks)
So I cannot simply increment a char, I must use a string array.
Nivm – your line: “if (eachChar=127)” is actually assigning 127 to the variable eachChar. Depending on the result of that operation, you may be causing the “if” to fail, or it’s just looking at the result of that operation and then executing the next line which is the return 0;.
You can increment a char. You do not need a string. Incrementing a string doesn’t make any sense (at least in C).
Oh yeah, you need the comparison == for the if.
I have this odd feeling Alex just isn’t looking here anymore.
I want to compare strings with each other but i run in some serious problems.
String which I have declared in the exact same way when compared with each other
give a false (0) in stead of true (1). Here is an example:
#include <iostream> #include "math.h" using namespace std; int main() { char sss[]={'s', 'i', 'n'}; char ddd[]={'s', 'i', 'n'}; bool cmp; cmp=(sss==ddd); cout<<cmp; return 0; }This reterns 0.
so does this:
#include <iostream> #include "math.h" using namespace std; int main() { char sss[]="sin"; char ddd[]="sin"; bool cmp; cmp=(sss==ddd); cout<<cmp; return 0; }What is the problem when comparing strings. Is it that null operator at the end or what?
I have done conversion to an integer and even that does not come out the same. In the case above it is the last two digits that come up different.
Can someone explain this to me.
I’m guessing it has something to do with the [].
correct me if I’m wrong pros, taking a guess. Started learning c++ (first lang ever) last week, so I might be wrong on my theory)
the [] will make both of them different even if the values are the same… so try this…
char sss='sin'; char ddd='sin';Just testing myself in problem solving. please correct me if I’m wrong.
EDIT**
The reason they are different is because your pulling up the address into the equation by using []. i believe.. because your dealing with arrays.
Using [] declares the variable as an array of characters. An array is different than a string and is different than one character… but each element of the array is one character. Unlike a string, the array is not terminated by a zero (null), unless you put one there.
If you compare each element of the array one for one (zero to zero, one to one and two to two) each element will give ’1′ for the match. In my tests, I made each array larger:
={‘s’, ‘i’, ‘n’, ‘s’}; and if you compare sss[0] to ddd[0] or sss[0] to ddd[3] they match.
To compare strings you will have to use a string-compare function. (I haven’t gotten that far yet. Just recalling unix shell and C code from my past.
Alright, so I picked up a few ideas from replies on here.
I just want some verification on my idea. I’m pretty sure it will work and going to test it out after this reply..
anyways to get to it.
the
SYSTEM("");cmd is some sort of source for calling dos commands? if this is true… I could use code
SYSTEM("MKDIR C:?.*");to make a structure directory program ??? based upon the user’s
< input? right??
And would arrays be a better idea on structuring?
thanks for the look over.
I'm in college atm and i end up making a million nested directories.. for which i use dosprompt for) (goes faster in my opinion).
Alex, thanks for the info!
From my background I’ve used binary, octal, hex and decimal when referring to characters, so please make sure above when you say an ‘a’ is 97 you specify that it’s (it is) a decimal 97. Granted the compiler assumes decimal, but readers may not.
Also, “The following program asks the user to input a character, then prints out both the character and it’s ASCII code:” Please check in all the tutorials each use of “it’s” which is short for “it is” and is never possessive. “its” is possessive just is his, hers and theirs are possessive and you do not use an apostrophe for them.
Pathik asked “Why do you need ‘/?’…. we can use question mark with cout….” and Alex responded with “Honestly, I don’t know. :)”. Pathik’s example used “?”.
From my years of C coding, single quotes enclose one character and double-quotes enclose a string. Strings were (are?) far different than a char – mostly in storage (memory) and using them. Strings are one or more characters and terminated (usually with a zero – not the character 0, but all zero bits). Strings always take up more than 8 bits (one byte).
cout may not care, but your variable declaration (compiler) may be particular about it and/or your code may not work.
The slash question mark may be used in case a compiler interprets question marks as something else. This depends on your compiler, IE, it’s just to make sure your code really does (compiles to) what you want it to do. Some pattern matching (MS Word?) use a question mark to substitute/match a single character, and to match a question mark you have to escape it. Same thing may be for some compilers.
In the following example above:
char chValue = ’5′; // assigns 53 (ASCII code for ’5′)
char chValue2 = 5; // assigns 5
Does the bottom statement assign 5 or does it assign the character associated with the ASCII code for 5 (i.e. a club symbol)?
Thanks
How come on one of the codes above it says
#include “iostream”; ?
Shouldn’t it be
#include ?
Just saying.
Yeah, he made a mistake there, and hasn’t fixed it.
Do programmers have to memorize escape sequences and stuff? It would be helpful if there was a single page with all the reference tables in it.. I’ll just bookmark ‘em for now (;
You just remember them naturally after using them dozen of times. Also, there’s always google, should you forget any of them :p
Please i need some help here.
For example on these lines of code
char = cchar;
cin>> cchar;
if i input 10 at cchar it stores 10 as a string or as an integer?
i made the code below to make a test in order to get the
answer on the question that is above
char cchar;
cin>>cchar;
char cchar2 = 5;
cout<<cchar+cchar2<<endl;
cout<<cchar+(int)cchar2;
i input 5 and it gives me a sum of 58
on both couts, this make me understand that it takes
the input of cchar as string because as you said in the tutorial:
char chValue = '5'; // assigns 53 (ASCII code for '5')
but i cant understand why at the second cout it takes (int)cchar2 as 53 shouldnt it have the value of 5 because of the (int).
Please an answer would be appreciated.
You answered your own question – it stores 53, because as you said, it stores the ASCII code. when you add the (int), nothing changes, because cchar2 already has an int in it (53), hence it still thinks of it as 53.
If this function were to run properly, shouldn’t it return an integer at the end?
#include “iostream”;
int main()
{
using namespace std;
char chChar;
cout <> chChar;
cout << chChar << " has ASCII code " << (int)chChar << endl;
}