Group,
I am teaching myself c++. I have been using a variety of sources and have landed on C++ Primer. Very good, easy to follow.
I am having a problem making one of the example programs work. The code from page 95 is below. I am sure I have copied it correctly.
It works if I take out the while statement and put in
cin << n;
instead. That gives an answer of
Your hex number is: C
for an input of 12.
The program with the while statement is suppose to give an answer of:
Your hex number is: C05F8F
for an input of: 12 0 5 15 8 15
This is the third printing of this book so I am assuming that there is no typo. This book does have an annoying habit of using code from previous paragraphs as part of an example that they are talking about. But I have been able to figure most of that out.
The question is what am I missing here?
Thank you in advance for your help,
Dan
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main () {
const string hexdigits = "0123456789ABCDEF";
cout << "enter a series of numbers between 0 and 15"
<< " separated by spaces. Hit ENTER when finished: " << endl;
string result;
string::size_type n;
while (cin >> n)
if (n < hexdigits.size())
result += hexdigits[n];
cout << "Your hex number is; " << result << endl;
}
First,
The error that I am getting is a no response. I put in the input and get a blank line
Second,
Yes, if I do ctrl + z I get the correct answer.
Why? Do I have my IDE setup wrong?
Again, thanks for your time,
Dan
This is checking if the input is fine(true/false) and at the same time requesting an input from the user. Alt + z request an end-of-file. I think it means that the cin has reached its' limit so it can't handle anymore input, so the condition returns false and you break out of the loop.
You can also break out of the loop by inputting a type that cannot be converted to the type of the variable that you're inputting to, causing the cin to fail. Try after inputting the numbers, enter in alphabets. Characters cannot be converted to string::size_t, cin fails, breaks out of the loop, print.
Okay,
I see that ctrl z forces an end to the loop.
Did the authors expect me to do this and that is what I missed?
How would I code in an end to the loop?
I will work on that question.
Thanks for all your help,
Dan
What I have learned
The while loop will go on forever unless ended somehow.
ctrl + z is a user input method to end the loop
inputting an out of bounds integer is just ignored
inputting other than integer causes failure in the loop and forces a quit
I could use an increment method to shut down the loop after a certain number of inputs, also.
Again, thanks for the help,
Dan