Reputation: 25
How can I store a string command line argument in to a self defined string variable. As it tend to give "Array Index out of Range Bounds"...
Here is the code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Prac1_e
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a String and a number : ");
Console.Read();
string str = args[0];
int n = Convert.ToInt32(args[1]);
Console.WriteLine(str);
Console.WriteLine(n);
Console.ReadKey();
}
}
}
Upvotes: 1
Views: 1968
Reputation: 573
If you intend to read arguments passed in run-time from command line, you would need to read from Console
object. You can try this code.
static void Main(string[] args)
{
Console.WriteLine("Enter a String and a number : ");
string str = Console.ReadLine();
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(str);
Console.WriteLine(n);
Console.ReadKey();
}
Upvotes: 0
Reputation: 311316
You are attempting to access the first two command line argument (agrs[0]
and args[1]
), but aren't passing any. Just pass some arguments and you should be fine:
Program somearg anotherarg
Upvotes: 1
Reputation: 4182
Arguments need to be passed via the command line in the format appname.exe "arg1" "arg2"
etc. Also, since you are converting to an Int
, you may want to validate that arg[1]
is convertible to an Int
.
static void Main(string[] args)
{
Console.WriteLine("Enter a String and a number : ");
Console.Read();
if(args.Length >= 2)
{
string str = args[0];
int n = Convert.ToInt32(args[1]);
Console.WriteLine(str);
Console.WriteLine(n);
Console.ReadKey();
}
else
{
Console.WriteLine("No Args passed");
}
}
If you are looking to capture runtime parameters via command-line, you would need to do something like the following:
static void Main(string[] args)
{
Console.WriteLine("Enter a String and a number, with a space between: ");
string consoleRead = Console.ReadLine();
string[] parsed = consoleRead.Split(' ');
if (parsed.Length > 1)
{
string str = parsed[0];
int n = Convert.ToInt32(parsed [1]);
Console.WriteLine(str);
Console.WriteLine(n);
Console.ReadKey();
}
}
Upvotes: 0
Reputation: 1180
No error in this code. But you will get above error, when you execute the program incorrectly. this should be the correct way:
[program name] [argument 1] [argument 2]
ex:
testprogram arg1 5
Upvotes: 0