I just started learning C++ this week, and I've been experimenting with different concepts. I wrote the program below to see what happens. Eventually, I want to make a code-breaking game.
#include<iostream>
using namespace std;
int main ()
{
char code[4], guess[4];
cout << "Enter the code: ";
cin >> code;
cout << "Enter the guess: ";
cin >> guess;
I have literally no idea why this worked, but when I switched the order that the user inputs the numbers (guess then code), it outputted "1234" for each one.
Edit: just switched the order back and it still works, even though it didn't before. Weird.
code and guess both have storage for 4 chars. Using cin>>code and cin>>guess requires storage for 5 chars each (assuming you enter 4-char strings,) so you are trampling memory you don't own.
Welcome to the wild and wonderful world of undefined behavior.
I tried switching it back (code then guess) and it didn't work again. 'Guess then code' works fine though. Yes, it is very strange... Thanks for your help though!
As cire pointed out, doing cin >> into an array is dangerous. Moreover, because you're not preventing buffer overflow, it makes your program hackable in the worst possible way: a malicious user can trick it to execute arbitrary code.
Or at least limit the input to the size of your buffers:
1 2 3 4 5 6 7
char code[4], guess[4];
cout << "Enter the code: ";
cin >> setw(4) >> code;
cin.ignore(1000, '\n'); // in case you entered too much
cout << "Enter the guess: ";
cin >> setw(4) >> guess;
(although you may want to make them code[5] and setw(5), if you want to enter four-characters trings)