从控制台读取值

本文关键字:读取 控制台 | 更新日期: 2023-09-27 18:30:40

我想知道C#中是否有类似C的scanf()printf()的东西?

String [] a1; 
String a = Console.ReadLine();
a1= s.split(); 
Int []  b; 
for(...) {b[i] = Int32.Parse(a1[i])}...

我可以做类似scanf("%d %d %d %d %d", &a, ..., &e);的事情?

从控制台读取值

C# 最接近printf的东西是Console.WriteLine(或输出到字符串String.Format)。 语法不同,但概念相同。 例如 printf("%4.2f",100)变得Console.WriteLine("{0:0.00}",100);

没有等同于scanf. 您需要使用 Console.ReadLine 并手动解析字符串。

环顾四周后,似乎 c# 没有实现 scanf

但是,您可以使用正则表达式来执行相同的操作。

但是,它确实以 String.Format() 的形式具有等价的 printf

int i = 5;
double d = 5.0;
String.Format("this is an int:{0}, this is a double:{1}", i, d);
  [DllImport("msvcrt.dll", CharSet = CharSet.Ansi, CallingConvention =  CallingConvention.Cdecl)]
  public static extern int scanf(string buffer, string format, ref int arg0, ref int arg1);

我认为,这将使您在 C# 中使用 scanf:)

如果没有,您必须使用拆分和转换:)