楼主这段代码很乱,有错误,比如str[i++]=ch;这两句是非法的,因为str中没有元素,貌似是楼主想用char 数组
下面是我按楼主思路写的
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
void GetKey(string &str);
int main()
{
string str_key ;
GetKey(str_key);
cout << '\n' << str_key << endl;
system("pause");
return EXIT_SUCCESS;
}
// I think forcing the buffer to be processed after each insertion may not be necessary
void GetKey(string &str)
{
string::iterator i_str;
cout << "password: " ;
char ch;
while((ch = getch()) != '\r') {
if(ch != '\b'){
str += ch;
cout <<'*';
}
else{ //backspace,modify the string
i_str = str.end()-1;
//we can never use the elements before the one str.begin() points to
if ( i_str != (str.begin()-1)) {
cout << "\b \b";
str.erase(i_str);
}
else
continue;
}
}
}
Dev C++ 4.9.9.2,Borland C++5.5编译通过,我没有VC,所以没试