C#循环输入学生姓名问题求助:如何保存并输出所有输入姓名
Hey there! I totally get what's going on here—you're using a single string variable to hold each student's name, so every time you enter a new name, it overwrites the last one. That's why only the final student's name shows up when you print it out. Let's fix this by using a collection to keep track of all the names instead!
The Problem Breakdown
Your current code uses string Name = ""; which only holds one value at a time. Each loop iteration replaces the value of Name with the newest input, so by the end of the loop, it only remembers the last name you entered.
The Solution: Use a List to Store Multiple Names
Instead of a single string, we'll use a List<string>—this is a built-in C# collection that lets you store and manage multiple string values easily. Here's the revised code with explanations:
// Create a List<string> to store all student names (instead of a single string) List<string> studentNames = new List<string>(); Console.WriteLine("How many students names would you like to input?"); int numberOfStudents = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < numberOfStudents; i++) { // Use i+1 here so student numbers start at 1 (friendlier for users) Console.WriteLine($"Enter name for student number: {i + 1}"); string name = Console.ReadLine(); // Add the newly entered name to our list studentNames.Add(name); } // Now print out all the names we stored Console.WriteLine("\nAll student names you entered:"); foreach (string name in studentNames) { Console.WriteLine(name); } // Alternative: Print all names in a single line separated by commas // Console.WriteLine("\nAll student names: " + string.Join(", ", studentNames)); Console.ReadLine();
Key Changes Explained
List<string> studentNames: This creates an empty list that will hold all the student names you input.studentNames.Add(name): Every time you enter a name, we add it to the list instead of overwriting a single variable.foreachloop: This loops through every name in the list and prints each one individually. If you prefer a more compact output, you can usestring.Jointo combine all names into a single string separated by commas (or any delimiter you want).i + 1in the prompt: Users usually expect to count starting at 1 instead of 0, so this small tweak makes the input process more intuitive.
That should do it—now your code will save every student name you enter and display all of them at the end!
内容的提问来源于stack exchange,提问作者solaturna

