While reading "C++ Primer Plus 5th edition", I saw this piece of code:
cin.get(ch);
++ch;
cout << ch;
So, this will lead to display the following character after ch. But, If I did it that way:
cin.get(ch);
cout << ch+1;
Now, cout will think ch is an int(try typecasting). So, why cout does so?
And why if I added 1 to a char it will produce a number?. And why there's a difference between:
ch++, and ch + 1.
The reason this occurs is the type of the literal 1 is int. When you add an int and a char you get an int, but when you increment a char, it remains a char.
Try this:
#include <iostream>
void print_type(char)
{
std::cout << "char\n";
}
void print_type(int)
{
std::cout << "int\n";
}
void print_type(long)
{
std::cout << "long\n";
}
int main()
{
char c = 1;
int i = 1;
long l = 1;
print_type(c); // prints "char"
print_type(i); // prints "int"
print_type(l); // prints "long"
print_type(c+i); // prints "int"
print_type(l+i); // prints "long"
print_type(c+l); // prints "long"
print_type(c++); // prints "char"
return 0;
}
Please note - this is the answe to the original question, which has since been edited.
Now, cout will think ch is an int(try
typecasting).
No it won't. It is not possible to change the type of a variable in C++.
++ch;
increments whatever is in ch.
ch + 1;
takes the value (contents) of ch, adds 1 to it and discards the result. Whatever is in ch is unchanged.
The statement ++ch; increments ch whereas ch + 1; doesn't.
Also, rememeber that '++ch' will do the increment before actually running the statement it is in, so that is why it remains a char.
int i = 0;
cout << ++i << endl;
cout << i++ << endl;
// both will print out 1.
Related
I am working on below code:
#include<iostream>
#include<stdio.h>
using namespace std;
main() {
unsigned char a;
a=1;
printf("%d", a);
cout<<a;
}
It is printing 1 and some garbage.
Why cout is behaving so?
cout << a is printing a value which appears to be garbage to you. It is not garbage actually. It is just a non-printable ASCII character which is getting printed anyway. Note that ASCII character corresponding to 1 is non-printable. You can check whether a is printable or not using, std::isprint as:
std::cout << std::isprint(a) << std::endl;
It will print 0 (read: false) indicating the character is non-printable
--
Anyway, if you want your cout to print 1 also, then cast a to this:
cout << static_cast<unsigned>(a) << std::endl;
I had a similar issue here that I've long forgotten about. The resolution to this problem with iostream's cout can be done like this:
#include<iostream>
#include<stdio.h>
main() {
unsigned char a;
a=1;
printf("%d", a);
std::cout<< +a << std::endl;
return 0;
}
instead of casting it back to another type if you want cout to print the unsigned char value as opposed to the ascii character. You need to promote it.
If you noticed all I did was add a + before the unsigned char. This is unary addition that will promote the unsigned char to give you the actual number representation.
User Baum mit Augen is responsible for reminding me of this solution.
You need to typecast a as integer as cout<< (int)(a);. With this you will observe 1 on the output. With cout << a;, the print will be SOH (Start of Heading) corresponding to ascii value of 1 which can't be printed and hence, some special character is observed.
EDIT:
To be more accurate, the cout statement should be cout << static_cast<unsigned>(a) as Nawaz has mentioned.
The C compiler has its own way of defining the type of the printed output, because you can specify the type of the output.
Ex:
uint8_t c = 100;
printf("%d",c);
so you can also print c as an int by %d, or char %c, string %s or a hex value %x.
Where C++ has its own way too, the cout prints the 8-bit values as a char by default. So, you have to use specifiers with the output argument.
You can either use:
a + before the name of the output argument
uint8_t data_byte = 100;
cout << "val: " << +data_byte << endl;
use a function cast unsigned(var); like,
uint8_t data_byte = 100;
cout << "val: " << unsigned(data_byte) << endl;
printf("%u",a);
its so simple try it
I did write this program but now I am little bit confused about it. In the code given below I did writ two different statements which print string on the screen, first one did not print anything but second one print a symbol.
#include<iostream.h>
main(){
int i = 1; char c;
cout << c << endl;
while (i <= 255){
c = i;
cout << c << endl;
i++;
}
}
Please explain me logic of this program. I am beginner of 'C' language so please explain it to me in details.
Thanks
See, as in your program you haven't initialised char c;
It must be initialised or hold some value before being printed!
int i; char c;
i = 1;
cout << c << endl; // initialsise c=something of char-type;
c = i;
cout << c << endl; //as initialised,so prints something
Second, as you have initialised this char variable c. Hence,it prints some symbol,probably an ASCII character!
First cout << c << endl; prints unitialized value c (it might be zero, so you don't see anything). But second call of this instructions prints value (char) 1 (you can see it).
When you initially printed the character 'c' then it does not have any value. When nothing is initialized in a character then it takes garbage value. Afterwards
int i=1;
char c = i;
It stores 1 in variable 'c' but as it is a character so on printing 'c' it shows the ASCII value of 1 which is ☺
It is same as doing->
cout << (char)i <<endl;
if you want to print the ASCII table then this code may help
for(int i = 1; i <= 255; i++) {
cout<<"ASCII VALUE OF "<<i<<" is "<<(char)i <<endl;
}
I am writing a hex to dec conversion function. The input is a single character which is converted to hex and returned back as a char.
Here is the function
char hex2dec(char inp)
{
char out;
cout << "inp:" << inp;
if(inp >= '0' && inp <='9')
{
out = (inp - '0');
cout << " out " << out;
}
else
{
out = (toupper(inp) - 'A' + 10);
cout << " out " << out;
}
return out;
}
When i pass '0' and 'A' to the function, the print i get is
inp:0 out
inp:A out
i.e nothing is printed in out.
I am not able to find the issue..Can anyone help?
What you are actually trying to print is ascii characters with codes [0-15] which are not printable characters ie you want to print 15 but you print "\x0f" etc
use:
cout << (int)out;
and you'll force cout to invoke method printing ints not chars - this will solve your issue.
..or more 'c++++ ish' ;-)
cout << static_cast(out);
..or this which for most looks weird:
cout << int(out);
Use int out instead of char out. cout prints char as a character not an integer. The ASCII values 0-15 are unprintable control characters.
the reason why u got an 'A' from print is that out is char ,and after 'A' - 'A' + 10, out is a character whose ascii value is 10 instead of integer 10. So u will get a character whose ascii value is 10 instead of getting 'A'.After checking the ascii table, that character is null,which can explain why u get nothing in the output.
Simply use std::stringstream for this purpose.
#include <iostream>
#include <sstream>
int main (int argc, char ** argv)
{
// use hex formatting
std::stringstream stream;
stream << std::hex << 'A';
// retrieve value of the hex input character
int value;
stream >> value;
std::cout << value << std::endl; // prints 10
// reset the stream
stream.str ();
stream.clear();
// also works for strings
stream << "0xABC" << std::endl;
stream >> value;
std::cout << value << std::endl; // prints 2748
return 0;
}
I am working on below code:
#include<iostream>
#include<stdio.h>
using namespace std;
main() {
unsigned char a;
a=1;
printf("%d", a);
cout<<a;
}
It is printing 1 and some garbage.
Why cout is behaving so?
cout << a is printing a value which appears to be garbage to you. It is not garbage actually. It is just a non-printable ASCII character which is getting printed anyway. Note that ASCII character corresponding to 1 is non-printable. You can check whether a is printable or not using, std::isprint as:
std::cout << std::isprint(a) << std::endl;
It will print 0 (read: false) indicating the character is non-printable
--
Anyway, if you want your cout to print 1 also, then cast a to this:
cout << static_cast<unsigned>(a) << std::endl;
I had a similar issue here that I've long forgotten about. The resolution to this problem with iostream's cout can be done like this:
#include<iostream>
#include<stdio.h>
main() {
unsigned char a;
a=1;
printf("%d", a);
std::cout<< +a << std::endl;
return 0;
}
instead of casting it back to another type if you want cout to print the unsigned char value as opposed to the ascii character. You need to promote it.
If you noticed all I did was add a + before the unsigned char. This is unary addition that will promote the unsigned char to give you the actual number representation.
User Baum mit Augen is responsible for reminding me of this solution.
You need to typecast a as integer as cout<< (int)(a);. With this you will observe 1 on the output. With cout << a;, the print will be SOH (Start of Heading) corresponding to ascii value of 1 which can't be printed and hence, some special character is observed.
EDIT:
To be more accurate, the cout statement should be cout << static_cast<unsigned>(a) as Nawaz has mentioned.
The C compiler has its own way of defining the type of the printed output, because you can specify the type of the output.
Ex:
uint8_t c = 100;
printf("%d",c);
so you can also print c as an int by %d, or char %c, string %s or a hex value %x.
Where C++ has its own way too, the cout prints the 8-bit values as a char by default. So, you have to use specifiers with the output argument.
You can either use:
a + before the name of the output argument
uint8_t data_byte = 100;
cout << "val: " << +data_byte << endl;
use a function cast unsigned(var); like,
uint8_t data_byte = 100;
cout << "val: " << unsigned(data_byte) << endl;
printf("%u",a);
its so simple try it
I'm studying in this book (self study) and I'd really appreciate if you could help me with a little 'try this' exercise.
This is the code I wrote:
#include "../../../std_lib_facilities.h"
int main()
{
for (char i ='a'; i <='z'; ++i) {
int x = i;
cout << i << '\t' << x << '\n';
}
keep_window_open();
return 0;
}
The next step, according to the book, is: "[...] then modify your program to also write out a table of the integer values for uppercase letters and digits"
Is there a function to do that, or do I simply have to repeat the loop starting from A?
Thanks
Yes, repeat the loop from 'A' to 'Z' and '0' to '9'.
Assuming your book has covered functions (which it may not have), you might refactor your for loop into its own function perhaps called displayCharactersInTable which takes as arguments the first character and last character. Those would replace the use of 'a' and 'z' in the loop. Thus your main function would look like:
...
displayCharactersInTable('a', 'z');
displayCharactersInTable('A', 'Z');
displayCharactersInTable('0', '9');
...
const char lc_alphabet[] = "abcdefghijklmnopqrstuvwxyz";
const char uc_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int main() {
for (const char *cur = lc_alphabet; cur < lc_alphabet + sizeof(lc_alphabet); ++cur)
std::cout << *cur << \t << (int)*cur << '\n';
for (const char *cur = uc_alphabet; cur < uc_alphabet + sizeof(uc_alphabet); ++cur)
std::cout << *cur << \t << (int)*cur << '\n';
return 0;
}
This code does not assume that character representations are contiguous (or even increasing alphabetically), so it will work for all character encodings.
int b = 97; // the corresponding decimal ascii code for 'a'
int a = 65; // the corresponding decimal ascii code for 'A'
for(int i = 0; i < 26; ++i)
cout << char('A' + i) << '\t' << a << '\t' << char('a' + i) << '\t' << b << '\n'; //print out 'A' and add i, print out a, print out 'a' and add i, print out b
++a; //increment a by 1
++b; //increment b by 1