Hi!
I'm just learning C++ and found something weird - I have the following program:
[code=c++]#include <iostream>
int main()
{
std::cout << "Please enter a positive integer: ";
int n;
do
{
std::cin >> n;
std::cout << "You entered " << n << ".\n";
if(n<=0)
std::cout << "I said, a positive integer! :-P ";
} while(n <= 0);
for(int i=1; i<=n; i++)
{
std::cout << i << ". Some text\n";
}
std::cout << "Oh, I almost forgot:\n" << (n+1) << ". More text\n";
}
[/code]Now, it works fine, as long as I enter an integer. But if I enter a letter, it always shows
or a sligtly different number.
It's the same number for any letter, although that constant number changes sometimes after recompiling. It seems to be related to the amount of characters in my code or something like that.
I tried the following:
[code=c++]
do
{
// the same as before
} while(n <= 0 || n >= 134515049);
[/code]and got an output like this:
My thought was, that maybe it's reading the endl symbol as well, but I've no idea, what I can do against that.
Actually, I'd like to either avoid the user entering letters or interpret them as their ASCII-number or something like that.
Now, why does it give me these weird numbers and how can I get it to work as it should?
Greetings,
Nepomuk
I'm just learning C++ and found something weird - I have the following program:
[code=c++]#include <iostream>
int main()
{
std::cout << "Please enter a positive integer: ";
int n;
do
{
std::cin >> n;
std::cout << "You entered " << n << ".\n";
if(n<=0)
std::cout << "I said, a positive integer! :-P ";
} while(n <= 0);
for(int i=1; i<=n; i++)
{
std::cout << i << ". Some text\n";
}
std::cout << "Oh, I almost forgot:\n" << (n+1) << ". More text\n";
}
[/code]Now, it works fine, as long as I enter an integer. But if I enter a letter, it always shows
Code:
You entered 134515049.
It's the same number for any letter, although that constant number changes sometimes after recompiling. It seems to be related to the amount of characters in my code or something like that.
I tried the following:
[code=c++]
do
{
// the same as before
} while(n <= 0 || n >= 134515049);
[/code]and got an output like this:
Code:
You entered 134515065. You entered 134515065. You entered 134515065. You entered 134515065. You entered 134515065. You entered 134515065. ...
Actually, I'd like to either avoid the user entering letters or interpret them as their ASCII-number or something like that.
Now, why does it give me these weird numbers and how can I get it to work as it should?
Greetings,
Nepomuk
Comment