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