I used to code in C language in the past and I found the scanf
function very useful.
Unfortunately, there is no equivalent in C#.
I am using using it to
I think you want the C# library functions either Parse or Convert.
// here's an example of getting the hex value from a command line
// program.exe 0x00080000
static void Main(string[] args)
{
int value = Convert.ToInt32(args[1].Substring(2), 16);
Console.Out.WriteLine("Value is: " + value.ToString());
}
If regular expressions aren't working for you, I've just posted a sscanf()
replacement for .NET. The code can be viewed and downloaded at http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net.
Try importing msvcrt.dll
using System.Runtime.InteropServices;
namespace Sample
{
class Program
{
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int printf(string format, __arglist);
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int scanf(string format, __arglist);
static void Main()
{
int a, b;
scanf("%d%d", __arglist(out a, out b));
printf("The sum of %d and %d is %d.\n", __arglist(a, b, a + b));
}
}
}
which works well on .NET Framework. But on Mono, it shows the error message:
Unhandled Exception:
System.InvalidProgramException: Invalid IL code in Sample.Program:Main (): IL_0009: call 0x0a000001
[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidProgramException: Invalid IL code in Sample.Program:Main (): IL_0009: call 0x0a000001
If you need Mono compatibility, you need to avoid using arglist
using System.Runtime.InteropServices;
namespace Sample
{
class Program
{
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int printf(string format, int a, int b, int c);
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int scanf(string format, out int a, out int b);
static void Main()
{
int a, b;
scanf("%d%d", out a, out b);
printf("The sum of %d and %d is %d.\n", a, b, a + b);
}
}
}
in which the number of arguments is fixed.
Edit 2018-5-24
arglist
doesn't work on .NET Core either. It seems that calling the C vararg function is deprecated. You should use the .NET string API such as String.Format
instead.
Since the files are "semi-structured" can't you use a combination of ReadLine() and TryParse() methods, or the Regex class to parse your data?
You can use scanf directly from C runtime libraries, but this can be difficult if you need to run it with different parameters count. I recommend you to regular expressions for you task or describe that task here, maybe there is another ways.
There is good reason why a scanf like function is missing from c#. It's very prone to error, and not flexible. Using Regex is much more flexible and powerful.
Another benefit is that it's easier to reuse throughout your code if you need to parse the same thing in different parts of the code.