tags:

views:

3319

answers:

5

I used to code in C language in the past and I found the scanf function very usefull. Unfortunately, there is no equivalent in C#.

I am using using it to parse semi-structured text files.

I found an interresting example of scanf implementation here. Unfortunately, it looks old and uncomplete.

Do anyone knows a scanf C# implementation ? Or at least something that would work as a reversed string.Format ?

+5  A: 

Since the files are "semi-structured" can't you use a combination of ReadLine and Try.Parse() or Regex to parse your data?

Mitch Wheat
Sure I could :) However, scanf is so confortable and handy compared to regex. I am pretty sure it worth the effort.
controlbreak
Regex is not so bad. Download one of the free tools (like Expresso) and regexes are mu7ch easier to create and use.
Mitch Wheat
Thank you for the hint
controlbreak
AAT
+3  A: 

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.

Dmitriy Matveev
Ow, I have no clue about how to use directly C runtime libraries. I'd rather avoid it and stick to regexes instead.
controlbreak
A: 

You could use System.IO.FileStream, and System.IO.StreamReader, and then parse from there.

SMB
Yes, this is a mandatory condition to use ReadLine as Mitch Wheat suggested.
controlbreak
+1  A: 

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());
}
Nichol Draper
+2  A: 

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.

sprite