I'm using Bjarne Stroustrup's "Programming: Priciples and Practice Using C++" and have run into a problem in the Drill Exercise for Chapter 4. Step 1 has the reader write a while loop that reads in two ints and outputs them. To terminate one is to enter '|'. The problem is that I obviously don't understand how to cast an int to char. I have read multiple posts in this forum, such as:
http://www.cplusplus.com/forum/general/103477/
to no avail. My original attempt is as follows:
#include <iostream>
using namespace std;
int main()
{
cout<<"Please enter pairs of integers, pressing 'enter' between sets.\n";
cout<<"Press '|' to quit.\n";
int tmp1;
int tmp2;
bool stop = 0;
while(stop == 0){
cin>>tmp1>>tmp2;
if((char) tmp1 == '|') stop = 1;
cout<<"\t"<<tmp1<<"\t"<<tmp2<<"\n";
}
cout<<"\nDone.";
return 0;
}
When this is run, it outputs the input ints but when '|' in entered, the program doesn't terminate but outputs a '0' and 'the entered int' forever, until I shut down the command prompt window. If I entered '|' as the second input, then the continuous output is 'the entered int' and '0'. I figured that the '|' was stored as '0' and so wrote the following code to see what the input was stored as:
#include <iostream>
using namespace std;
int main()
{
cout<<"Please enter pairs of integers, pressing 'enter' between sets.\n";
cout<<"Press '|' to quit.\n";
int tmp1;
cin>>tmp1;
cout<<"You entered: "<<tmp1<<" using tmp1.\n";
cout<<"Or: "<<(char) tmp1<<" using (char) tmp1.\n\n";
char temp1 = static_cast<char>(tmp1);
cout<<"temp1 shows that you entered: "<<temp1<<"\n";
char temp2 = (char)tmp1;
cout<<"temp2 shows that you entered: "<<temp2<<"\n";
return 0;
}
The outputs for an int, such as 2, are (in order): 2, glyph, glyph, glyph
The outputs for a char, such as |, are (in order): 0, blank, blank, blank
It's not that my while loop doesn't have problems, but first casting an int to a char such that a non-int can be properly handled in code. So, my question is is there a good reference that explains how to handle an int such that I can write the code that Bjarne is asking for?