简体   繁体   中英

C++ Manipulating Strings, can print index chars but not complete string

I am trying to mask a password for a project I'm doing on OS X. Every masked character is appended to the string named password. But when I try to print or use the string I get nothing. However if I try to print an element of the string, I am able to. Example. cout<< password; wont print anything but cout << password[0] will print the first character of the string.

What am I doing wrong?

#include <termios.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>

using namespace std;
int getch();
int main(){
    char c;
    string password;
    int i=0;
    while( (c=getch())!= '\n'){
        password[i]=c;    
        cout << "*";
        i++;
    }

    cout<< password;
    return 0;
}
int getch() {
    struct termios oldt, newt;
    int ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}

When you define the object password it is starting out as empty which means any indexing into it will be out of bounds and lead to undefined behavior .

You don't need the index variable i , and you should append characters to the string:

password += c;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM