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

C#代码无法读取/打印内容,循环填充数组遇问题求助

问题分析与解决方法

问题1:循环中多余的输入读取

你在第一个for循环里写了两次Console.ReadLine():

sol[i] = Console.ReadLine();
Console.ReadLine();

第一次读取的是士兵姓名并存入数组,第二次会额外等待一次输入。这就意味着你输入s个名字后,程序还在等待你输入另外s次内容,所以你误以为输入后没有输出,实际是程序还没执行到排序和输出的步骤。

问题2:程序执行后直接关闭

当你移除多余的Console.ReadLine()后,程序会快速完成所有代码逻辑,然后立即关闭控制台窗口,导致你看不到输出结果。这是控制台程序的默认行为,需要在程序末尾添加暂停代码来阻止窗口马上关闭。

修正后的完整代码

using System;
using System.Collections.Generic;

int s = 0;
Console.WriteLine("How many soldiers: ");
s = Convert.ToInt32(Console.ReadLine());
string[] sol = new string[s];
Console.WriteLine($"Enter names of {s} soldiers");

for (int i = 0; i < sol.Length; i++)
{
    // 只保留一次输入读取,存入数组
    sol[i] = Console.ReadLine();
}

Array.Sort(sol);
Console.WriteLine("Names in order: ");

for (int i = 0; i < sol.Length; i++)
{
    Console.WriteLine(sol[i]);
}

Console.WriteLine("it works");
// 添加暂停,等待用户按键后再关闭窗口
Console.ReadKey();

额外实用提示

  • 用字符串插值$"Enter names of {s} soldiers"代替字符串拼接,代码更简洁易读。
  • 建议给输入做有效性验证,避免用户输入非整数导致程序崩溃,比如把数量输入部分改成:
Console.WriteLine("How many soldiers: ");
while (!int.TryParse(Console.ReadLine(), out s) || s <= 0)
{
    Console.WriteLine("请输入有效的正整数:");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:09:26