输入3个以上字符代码运行错误?

做了个输入密码回显星号的代码,但输入超过3个字符就运行错误,求助!

password.cpp

#include <iostream>
#include <string>
using namespace std;
#include "_INCLUDES_\password.h"
string pwd = "\0";
int main(int argc,char *argv[]) {
 pwd = getpassword();
 cout << "Your password is:\t" << pwd << endl;
 return 0;
}

password.h

#include <conio.h>
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;
string getpassword() {
 string str = "\0";
 int i = 0;
 for (;;) {
  str[i] = getch();
  if (str[i] == '\n') {
   cout << endl;
   str[i] = '\0';
   break;
  }
  else cout << "*" << flush;
  ++ i;
 }
 return str;
}

求助各位大佬!!!

password.h建议改成这样:

#include <conio.h>
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;
string getpassword() {
    string str = "";
    for (;;) {
        char t = getch();
        if (t == '\r') {    //我的电脑是\r
            cout << endl;
            break;
        } else {
            str += t;
            cout << "*" << flush;
        } 
    }
    return str;
}

我的电脑是认为\r是按下回车,具体情况看你自己的电脑。对于string不要直接用下标来添加数据,这样可能会溢出,用+=来添加数据就好了。注意string不是以\0为结尾的。

string str = "\0";
->
char str[100];
str[0] = '\0';