One problem in OP's code is the insufficient amount of memory allocated for the variables. For example, with those lines:
char id[7];
cin.getline(id,7);
The function getline
can read and store from the input stream up to 6 chars in the null terminated char array id
, but then the program has to compare that string to PLAYNOW
, which is 7 chars long.
This leads to next problem, when getline leaves unread chars in the stream, the failbit is set, preventing any further readings.
To fix those, even with the old standard, OP can do something like this:
const int ssize = 32; // enough space to store id or password
const int ssmax = 1024;
// big value... ^^ try std::numeric_limits<std::streamsize>::max() instead
char id[ssize],
pass[ssize];
cout << "Enter id: ";
cin.getline(id, ssize); // extract (ssize - 1) chars from input
if ( cin.fail() ) {
cin.clear(); // if user entered more then ssize chars
cin.ignore(ssmax, '\n'); // clear the stream
}
The same for pass
(OP didn't pass 8 to the second getline, too).
Then, the declarations of the strings which contain the expected ID and password are wrong. Use those:
char idc[] = "PLAYNOW";
char passc[] = "PASSWORD";
The last lines could be rewritten too:
if ( strcmp(id, idc) != 0 || strcmp(pass, passc) != 0 )
exit(0);
cout << "Welcome. ";
cin.get();
return 0; // end of main()
BTW, I'm quite sure that std::strings belonged to C++98, so this should work too:
#include <iostream>
#include <string>
int main() {
std::string id, pass;
std::cout << "Enter id: ";
std::getline(std::cin, id);
std::cout << "Enter pass: ";
std::getline(std::cin, pass);
std::string idc("PLAYNOW");
std::string passc("PASSWORD");
if ( idc != id || passc != pass )
exit(0);
std::cout << "Welcome. ";
return 0;
}