Mauricio Duran
Mauricio Duran

Reputation: 23

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;
}

Upvotes: 0

Views: 34

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409364

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;

Upvotes: 1

Related Questions