如何合并两个控制台程序:将程序1输出作为程序2输入且无需用户交互
Alright, let's tackle this exactly how you need it: we'll get Program 1's output feeding straight into Program 2, hide Program 1's console output entirely, and make sure Program 2 stops bugging the user for input. Here's the step-by-step fix:
1. Fix Program 1: Remove the Blocking ReadLine
Your current Program 1 ends with Console.ReadLine(), which makes it wait for user input before exiting—this breaks the pipe connection. We need Program 1 to spit out all its output and close immediately so it can pass data to Program 2 without hanging.
Modified Program 1 code:
foreach (var item in result) { Console.Write(item); } // Remove Console.ReadLine() entirely—no need to wait for user input here
2. Fix Program 2: Ditch the User Prompt
Program 2's opening prompt ("Please, enter numbers") is totally unnecessary now, since input is coming directly from Program 1. We'll delete that line so it doesn't clutter the console and doesn't imply user interaction is needed.
Modified Program 2 code (matching your snippet):
// Remove the Console.WriteLine("Please, enter numbers"); line entirely var numbersStr = Console.ReadLine(); if (!string.IsNullOrEmpty(numbersStr)) { // Your existing processing logic goes here // Example: Console.WriteLine($"Processed input: {numbersStr}"); }
Bonus: Handle Multi-Line Input (If Needed)
If Program 1 outputs multiple lines of data, update Program 2 to loop through all incoming input instead of just reading one line:
string inputLine; while ((inputLine = Console.ReadLine()) != null) { // Process each line from Program 1 Console.WriteLine($"Processed line: {inputLine}"); }
3. Run Them With a Pipe
To connect the two programs, open your command prompt (or PowerShell), navigate to the folder where your compiled .exe files live, and run this command:
Program1.exe | Program2.exe
- Program 1's output won't show up in the console—it's directly sent to Program 2's input stream.
- Program 2 won't ask for user input anymore; it just reads whatever Program 1 sends it.
That's it! This setup ensures seamless data flow between the two programs without any unwanted user interaction or visible output from Program 1.
内容的提问来源于stack exchange,提问作者user9612206

