#include <iostream>
using namespace std;
int main()
{
int loop = 0;
int Pass = 0;
int guess = 0;
cout << "Write In A 4 Digit Number!";
cin >> Pass;
while (loop == 0)
{
guess = guess + 1;
if (Pass == guess)
{
cout << "Your number is" + guess;
}
}
return 0;
}
This mystery code is giving me random outputs. This is a program ment to guess what number you put in. Instead when you input a random number and hit enter it gives you stuff like error and YF and stuff. Try it yourself by testing the code. If you type in 1 and press enter you will get our number is printed out.
There's some more odd also like if you enter 666 you will get: e::_S_normalize_catory catory not found and if you enter 333 ☻ will print out.
There's plenty more. Some numbers are blank but some are not.
Can someone please tell me why this happends!
CLOSED: THANKS FOR HELPING ME OUT. I CLOSE THIS NOW. YOU CAN STILL CHAT!
You need to change the
cout << "Your number is" + guess;
to
cout << "Your number is " << guess;
In C++, adding a number to a string literal doesn't convert the number to a string; it does something else entirely (pointer arithmetic).
For a backgrounder on pointer arithmetic in C and C++, see Everything you need to know about pointers in C (especially the last section about strings).
The reason your program prints out funny strings is that, once guess gets large enough, the "Your number is" + guess points to some memory after the end of the string literal, and the program prints out whatever happens to be in that memory. (Technically, you're in the realm of undefined behaviour and so your program could legitimately behave in all sorts of strange ways.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With