Search code examples
c++stringraw-input

Unknown character is being added to the last of the string


Below is a part of my application being designed in C++. The below code fragment displays *** as password input by user.The code is used in two places in the program one works fine and the other place it shows a unknown character at the end of enterdPassword.

It works fine here.the entered password is saved in a file for further use.

if(FirstRun()){
    display_welcome_text_first_run();

    cout<<"\nEnter A Password(Max 13 character): ";
    for(i=0; i<13; i++){
        x = getch();
        if(x == '\r'){ break; }
        putchar('*');
        p[i]=x;
    }

    p[i+1]='\0';
    string pwd(p);
    ofstream o(PASSWORD_FILE,ios::binary);
    o <<pwd<<endl;
    o.close();

Here it shows the error it shows a unknown character at the end of enterdPassword.

bool verifyPassword(){
    string savdPassword;
    char px[20], x;
    int i;
    cout<<"Enter Your Password To Continue: ";

    for(i=0; i<13; i++){
        x = getch();
        if(x == '\r'){ break; }
        putchar('*');
        px[i] = x;
    }
    px[i+1] = '\0';

    string enterdPassword(px);

    ifstream pp(PASSWORD_FILE, ios::binary);
    pp>>savdPassword;
    pp.close();
    cout<<endl<<enterdPassword;<<" "<<savdPassword; //for debugging
    if(enterdPassword == savdPassword){
        return true;
    }
    else{return false;}
}

Image of program run. Image of program run.

I don't understand why the same code(only with different variables) give work differently How can I correct the code to work correctly as desired?.


Solution

  • You have to change

    p[i+1]='\0';
    

    to

    p[i]='\0';
    

    because i has been already incremented after the last loop iteration.

    However, it's better not to use raw character arrays at all:

    string pwd;
    for(i=0; i<13; i++){
        x = getch();
        if(x == '\r'){ break; }
        pwd += x;
    }