簡體   English   中英

不能正確獲取命令行參數輸出

[英]Not Getting the Command Line Parameter Output Properly

我試圖顯示作為輸入輸入的命令行參數數。 這是我的代碼塊。

//Argument: A, B, C, D

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ParamaterCount
{
    public class ParameterCount
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
            Console.WriteLine("You have entered {0} command line arguments",args.Length);
            Console.ReadLine();
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine("{0}", args[i]);
            }
        }
    }
}

但是,當我嘗試運行它時。 它從屏幕上消失了,我什么也沒得到。 我還添加了Console.ReadLine()語句,但無法在For循環內部輸入以計算迭代次數。 我想念什么嗎? 謝謝。

輸出應該是這樣的。

Hello World,
You entered 4 Command Line Arguments
A
B
C
D

在控制台應用程序中,參數將無法那樣工作。 您的代碼還可以,但是請注意,您必須在運行時輸入參數,但是由於在運行時調用的第一個方法是Main()因此您沒有機會提供命令行參數。 為了實現所需的功能,必須從命令行運行已編譯的輸出應用程序,假設您的應用程序名稱為ConsoleApplication.exe ,因此請打開命令行,然后按如下所示運行ConsoleApplication.exe

ConsoleApplication.exe A B C …

有關更多信息,請參見: 命令行參數

BTW:你總是可以運行使用CTRL + F5代替F5控制台應用程序,因為如果你寫了這將產生相同的結果Console.ReadLine()在你的應用程序的結束。

您應該在Main方法的末尾移動Console.ReadLine()語句。 因此,您的代碼應如下所示:

public static void Main(string[] args)
{
    Console.WriteLine("Hello World");
    Console.WriteLine("You have entered {0} command line arguments",args.Length);

    for (int i = 0; i < args.Length; i++)
    {
        Console.WriteLine("{0}", args[i]);
    }
    Console.ReadLine();
}

嘗試:

 public static void Main(string[] args)
{
    Console.WriteLine("Hello World");
    Console.WriteLine("You have entered {0} command line arguments {1}",args.Length, string.Join(" ", args);

    Console.ReadLine();
}

從控制台運行程序時,除去console.readline()語句,而是提供輸入。 我對c#一無所知,但是在Java中,您可以按以下步驟完成上述任務。

javac s.java
java s A B C D

實際上 ,您不需要使用Console.ReadLine()因為它讀取輸入流,而不是您提供的參數。

那就是您只需要的代碼;

Console.WriteLine("Hello World");
Console.WriteLine("You have entered {0} command line arguments", args.Length);
for(int i = 0; i < args.Length; i++)
{
    Console.WriteLine("{0}", args[i]);
}

然后執行以下步驟;

  • Run並鍵入cmd.exe ,這是命令行的快捷方式
  • cd轉到您的exe文件夾(在我的示例中為cd C:\\Users\\Soner\\Documents\\Visual Studio 2012\\Projects\\ProgramConsole\\ProgramConsole\\bin\\Debug
  • 使用名稱和ABCD運行exe(在我的示例ProgramConsole.exe ABCD

輸出將是;

Hello World
You have entered 4 command line arguments
A
B
C
D

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM