Varible 2020-02-22 11:01 采纳率: 75%
浏览 377
已采纳

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

求助各位大佬!!!

  • 写回答

2条回答 默认 最新

  • Eyre Turing 2020-02-24 08:14
    关注

    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为结尾的。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误