Unable to typecast char to int. - c++

I am a high school beginner to C++ (Less than 1 month since I started). I have been trying to convert a int into its char value. (So, a 5 should convert to a '5')
I am aware how to convert from char to int (from '5' to 5), by subtracting 48 from it, however I am unable to cast the other way. Here's what I tried:
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout<<x<<endl;
cout<<(char)x<<endl;
cout<<static_cast<char>(x)<<endl;
cout<<"end of program"<<endl;
}
The output I get is
5
end of program
I am unsure why I don't get an output. Appreciate any advice.

The cast is working perfectly fine (for what you're doing).
You're casting a 5 to it's ASCII value. Look at an ASCII table and see what a 5 represents.
Now for what you're trying to do, try cout << (char)(x+48) << endl;

Try the following
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout << x << endl;
cout << ( char )( x + '0' ) << endl;
cout << static_cast<char>( x + '0' ) < <endl;
cout << "end of program" < <endl;
}
And you have not to look through ASCII table.:) Take into account that there is EBCDIC table. The code I showed does not depend on a coding table. The C++ Standard guarantees that all characters of digits follow each other starting from '0' to '9'.

Related

Strange symbols printing in C++ instead of array content [duplicate]

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

why in decimal to binary code it does not work properly when we enter numbers above 63?

i wrote a code that recives the numbers from the base ten and gives us the binary number.But for numbers above 64, it just doesn't work properly.and i don't know why.please help me.
#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int c; int b,a[c];
cin>>b;
for(c=0;b>1;c++)
{
a[c]=b%2;
b=b/2;
}
cout<<b;
c--;
for(c;c>=0;c--){
cout<<a[c];
}
getch();
The problem resides here:
int c; int b,a[c];
You are defining a Variable Length Array (not standard, btw) of size c, but you have not given c a value, therefore, this is undefined behaviour (use of c before giving it a value). Since you are dealing with integers, you can do int a[32] though, which should allow your code to work.
Another method with strings:
std::string str;
while ( b != 0 ) {
str = std::to_string( b % 2 ) + str;
b /= 2;
}
std::cout << str;
A few things to note:
main requires a return type, and should be int main()
conio.h is not standard, and shouldn't be used
int a[c] is a variable length array (VLA), not standard, and shouldn't be used.
using namespace std is a bad idea.
The problem has been pointed out in other answers so I'm just going to give you an alternative solution.
You could also try using bitset if your intent is to convert to binary.
#include <bitset>
using namespace std;
bitset<32> bv;
bv = 65;
cout << "Binary value " << bv <<"\n";
bv = 195;
cout << "Binary value " << bv <<"\n";

Compile error declaring my char vector array

I've done some self learning in the past with c++ online but gave up, till I bought a textbook on it and giving it another go. In my past research, I never read anything on vector arrays (or maybe I did and don't remember, who knows).
Anyway it says like regular arrays, vector arrays can be created for any data type and I'm trying to get a char vector array going and I'm running into some compile errors take a look.
I want an array of 26 that houses all the letters in the alphabet capitalized. So 65 to 91 I think. If there is and easier way to initialize the array with the letter I'm interested in learning that way.
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector <char> vchChar(26, 65);
for (int iii = 0; iii < vchChar.size(); iii++ )
{
for (int jjj = 65; jjj < 91; jjj++)
{
vchChar(iii) = jjj;
cout << "vchChar(" << iii+1 << ") is:\t" << vchChar(iii) << endl;
}
//cout << "vchChar(" << iii+1 << ") is:\t" << vchChar(iii) << endl;
}
return 0;
}
Originally I had square brackets instead of the parenthesise, fixed that and had hoped it would work but that got a whole set of new problems when I tried changing them in the cout statements. When I had them in square brackets it printed out in the terminal fine no compile errors. So now I have the cout statements like
cout << "vchChar(" << iii+1 << ") is:\t" << vchChar[iii] << endl;
I thought vector arrays where incremented by one from the element before it. But all I got when I printed vchChar into the terminal where all 'A's. So I tried playing around with another for loop to assign them by one from the element before it. I got some different outputs then I'd desired, and cant find the right algorithm to do it.
I'll keep at it, but an answer on this post is just as good for me. I have little idea what I'm doing so post everything you've got, but keep in mind that I probably wont have any idea what you're talking about :S. I've probably left something out because I've change the code a bit when troubleshooting, so if there are any question ask, and thank for your time.
I do not see any sense in your code. If I have understood correctly what you need is the following
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
std::vector<char> vchChar(26);
std::iota( vchChar.begin(), vchChar.end() , 'A' );
for ( char c : vchChar ) std::cout << c << ' ';
std::cout << std::endl;
return 0;
}
Or you can write it even the following way
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
std::vector<char> vchChar( 'Z' - 'A' + 1 );
std::iota( vchChar.begin(), vchChar.end() , 'A' );
for ( char c : vchChar ) std::cout << c << ' ';
std::cout << std::endl;
return 0;
}
If your compiler does not support standard algorithm std::iota and the range-based for statement then you can write
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
std::vector<char> vchChar( 'Z' - 'A' + 1 );
for ( char c = 'A'; c <= 'Z'; ++c ) vchChar[c - 'A'] = c;
for ( std::vector<char>::size_type i = 0; i < vchChar.size(); ++i )
{
std::cout << "vchChar[" << i << "] is:\t" << vchChar[i] << std::endl;
}
return 0;
}
Take into account that it is a bad idea to use magic numbers as 65 or 91. For example if the program will run in an IBM mainframe then the result will be unexpected because there is another coding system, that is EBCDIC instead of ASCII.
As for statement
vchChar(iii) = jjj;
then it is invalid. Expression vchChar(iii) means a call of the operator function with one argument that is not defined in class std::vector.
You have at least the following issues in your code:
Setting a vector element is not done by myVector(index), but myVector[index], so basically the operator[]. In this special case, however, you can just push them in a row to the back.
You are trying to print one element of the array with vchChar(iii), but you should use the .at(index) method.
It is not crucial, but in this special case, you could use the iterator pattern to go through the vector rather than dealing with the indexing. Even if you do not do that, it is needless to use iii and jjj for variable names instead of the regular i and j.
I would prefer to use size_t or the vector<char>::size_type for the loop counters as you compare one of them against the vector size.
You are setting the elements more than once because you have a nested loop.
You are needlessly constructing the vector differently than the default.
You are using hard coded integers rather than actual characters.
Therefore, your correct code would look like this:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector <char> vchChar;
for (char c = 'A'; c <= 'Z'; ++c)
vchChar.push_back(c);
for (vector<char>::size_t i = 0; i < vchChar.size(); ++i)
cout << "vchChar(" << i+1 << ") is:\t" << vchChar.at(i) << endl;
return 0;
}
Disclaimer: this is just compilation and runtime fix. I have not dealt with use case and design issues. There are better solutions as I partially mentioned them, but I decided to make your code with the least impact.
You do not need nested loops.
{
vector<char> vchChar;
for (char letter = 'A'; letter <= 'Z'; ++letter) {
vchChar.push_back(letter);
}
for (int i = 0; i < (int) vchChar.size(); ++i) {
cout << vchChar[i];
}
}

cout not printing unsigned char

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

C++ Confusion. Reading Integer From Text File. Convert to ASCII

I am learning C++ for the first time. I have no previous programming background.
In the book I have I saw this example.
#include <iostream>
using::cout;
using::endl;
int main()
{
int x = 5;
char y = char(x);
cout << x << endl;
cout << y << endl;
return 0;
}
The example makes sense: print an integer and the ASCII representation of it.
Now, I created a text file with these values.
48
49
50
51
55
56
75
I am writing a program to read this text file -- "theFile.txt" -- and want to convert these numbers to the ASCII value.
Here is the code I wrote.
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
using std::ifstream;
int main()
{
ifstream thestream;
thestream.open("theFile.txt");
char thecharacter;
while (thestream.get(thecharacter))
{
int theinteger = int(thecharacter);
char thechar = char(theinteger);
cout << theinteger << "\t" << thechar << endl;
}
system ("PAUSE");
return 0;
}
This is my understanding about the second program shown.
The compiler does not know the exact data type that is contained in "theFile.txt". As a result, I need to specify it so I choose to read the data as a char.
I read the each digit in the file as a char and converted it to an integer value and stored it in "theinteger".
Since I have an integer in "theinteger" I want to print it out as a character but char thechar = char(theinteger); does not work as intended.
What am I doing incorrect?
You are reading char by char, but you really (I think) want to read each sequence of digits as an integer. Change your loop to:
int theinteger;
while (thestream >> theinteger )
{
char thechar = char(theinteger);
cout << thechar << endl;
}
+1 For a very nicely formatted & expressed first question, BTW!
You are reading one char at a time from the file. Hence, if your file contains:
2424
You will first read the char "2" from the file, convert it to an int, and then back to a char, which will print "2" on cout. Next round will print "4", and so on.
If you want to read the numbers as full numbers, you need to do something like:
int theinteger;
thestream >> theinteger;
cout << char(theinteger) << endl;