-
strcat and a char
I am brand new and working through the tutorial. I know the following is probably a little messy, please excuse - I am learning the conventions.
I am having trouble with the strcat function. I want the program to ask for one character at a time and then, when four are collected and stored in "password" to check it for validity. I know there are probably other problems but I keep getting the compiler error on the "strcat" line.. so, if you see the problem with the "strcat" and any other problem, as well as pointing out any problems in my approach, I would greatly appreciate it.
Code:
int main(){
char a;
char password[4];
int x;
int y = 0;
while(y==0){
for(x=0; x<4; x++){
if(x==0){
cout << "Enter first pin: ";
}
else if(x==1){
cout << "Enter second pin: ";
}
else if(x==2){
cout<< "Enter third pin: ";}
else {
cout << "Enter fourth pin: ";}
}
cin >> a;
strcat(password, a); //I also tried "&a" - it compiled without error but the program was non-functional..
if(password == "1066"){
cout << "You have done it. You have entered the 4 magic numbers.";
y++;}
else if (strlen(password)<4){
cout << "Please enter more." << endl;}
else {
cout << "You have entered the incorrect four numbers. You have failed.";
cin.get();
return 1;
}
}
cin.get();
}
-
Instead of strcat, I would directly modify the char array with
password[x]=a;
but for future reference, strcat( destination, source), both destination and source must be NULL-Terminated
also, you can't compare c-string/char arrays this way:
if(password == "1066")
you will need to use if(strcmp(password, "1066"))
but then password again will need to be NULL-terminated so I would suggest:
char password[5];
password [4] = '\0';
finally, if you switch to using std::strings instead it will save you a lot of this trouble. For instance, strcat would simply be
password += a;
and comparison would work like you have it
if(password == "1066")
-
Perfect
Thank you much - exactly what I was looking for.