You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#控制台程序无法判断用户输入的密码是否正确该如何解决?

核心问题

Console.ReadLine()方法会返回用户在控制台输入的字符串内容,你的代码仅调用了该方法但没有将返回值赋值给userInput变量,导致userInput始终保持初始化时的String.Empty空值,无法完成正确的密码比对。
你之前尝试直接写userInput = password的操作相当于手动让两个变量相等,自然会出现无论输入什么内容都提示密码正确的问题。

修复方案
  • 把Console.ReadLine()的返回值赋值给userInput变量
  • 可将两次独立的if判断合并为if-else结构,减少重复校验,逻辑更清晰
修复后代码
string password = "abcd1234";
string userInput = String.Empty;
string Text1 = "Please Insert Your Password";
string Text2 = "Incorrect Password!";
string Text3 = "Correct You May Proceed!";

Console.WriteLine(Text1);
// 接收用户输入存入userInput变量
userInput = Console.ReadLine();

if (userInput == password)
{
    Console.WriteLine(Text3);            
}
else
{
    Console.WriteLine(Text2);
}
可选优化

如果需要实现不区分大小写的密码校验,可以替换判断逻辑为:
if (string.Equals(userInput, password, StringComparison.OrdinalIgnoreCase))

内容的提问来源于stack exchange,提问作者RappleTh3Apple

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:54:08