John Smith
John Smith

Reputation: 21

Reading values from console

I want to know if there are something like C’s scanf() or printf() in C#?

String [] a1; 
String a = Console.ReadLine();
a1= s.split(); 

Int []  b; 

for(...) {b[i] = Int32.Parse(a1[i])}...

I could do something like scanf("%d %d %d %d %d", &a, ..., &e);?

Upvotes: 2

Views: 4116

Answers (3)

Prettygeek
Prettygeek

Reputation: 2531

  [DllImport("msvcrt.dll", CharSet = CharSet.Ansi, CallingConvention =  CallingConvention.Cdecl)]
  public static extern int scanf(string buffer, string format, ref int arg0, ref int arg1);

That will let you use scanf in C#, i think:)

If not, you have to use split and convert:)

Upvotes: 1

D Stanley
D Stanley

Reputation: 152624

The closest thing C# has to printf is Console.WriteLine (or String.Format to output to a string). The syntax is different but the concept is the same. e.g. printf("%4.2f",100) becomes Console.WriteLine("{0:0.00}",100);

There is no equivalent to scanf. You need to use Console.ReadLine and parse the string manually.

Upvotes: 2

After some looking around, It seems like c# does not have an implementation of scanf.

You can, however, use regular expressions to do the same thing

it does, however, have an equivelant of printf in the form of String.Format()

int i = 5;
double d = 5.0;
String.Format("this is an int:{0}, this is a double:{1}", i, d);

Upvotes: 1

Related Questions