Looking for C# equivalent of scanf

后端 未结 9 1131
误落风尘
误落风尘 2020-11-29 09:51

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

9条回答
  •  爱一瞬间的悲伤
    2020-11-29 10:31

    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.

提交回复
热议问题