Hello swezafor,
Welcome to the forum.
PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
First you have to understand how "cin" works. Any type of input from the keyboard does not go directly to your variable, but into what is known as the input buffer.
If you were to type in from the keyboard "101Enter" the input buffer would contain "101\n" where "\n" is a newline. As the while loop loops the character "1" is extracted from the input buffer and the next line print the ASCII decimal value of "1". On the second loop the "0" is extracted and printed. The same for the third iteration of the loop leaving the "\n" left in the input buffer. On the next iteration the "\n" is extracted and printed now leaving the input buffer empty and waiting for new input from the keyboard.
An if statement could be added before the "cout" to check for the new line character and bypass printing the "10" that you see. You could also use this to print a new prompt to tell the user to enter a new number.
An if statement following the "cin" checking for a minus sign can be used to break out of the while loop and end the program.
This is an idea I had:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
int main()
{
char x;
std::cout << "Any number (negative number to exit): ";
while (true)
{
x = std::cin.get();
if (x == 45) // <--- The decimal number for the minus sign.
break;
if(x != 10) // <--- "10" for the new line. Could also be "13: on some systems.
std::cout << int(x) << " ";
else
std::cout << "\n\n Enter a new number (negative number to exit): ";
}
return 0;
}
|
Notice the use of blank lines to break up the program. This makes it easier to read and follow and the compiler does not care about extra white space.
Hope that helps,
Andy