2

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);?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
John Smith
  • 21
  • 1
  • 2
  • What's wrong with the code you have here? It looks like it works. – Linuxios Sep 09 '13 at 21:54
  • For `printf` there is `String.Format`. – Nemanja Boric Sep 09 '13 at 21:55
  • I know it works, but i wanna know if there are something "more easy" to reading my x integer numbers...? – John Smith Sep 09 '13 at 21:56
  • possible duplicate of [Looking for C# equivalent of scanf](http://stackoverflow.com/questions/472202/looking-for-c-sharp-equivalent-of-scanf) – ChrisK Sep 09 '13 at 21:56
  • Sure. `int[] readXIntegers(int x){ int [] data = new int[x]; var arr = Console.ReadLine().Split(new char[]{ ' ' }); for(int i = 0; i < x; i++){ data[i] = Int32.Parse(arr[i]); } return data; }` – Nemanja Boric Sep 09 '13 at 21:59

3 Answers3

2

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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

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);
1
  [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:)

Prettygeek
  • 2,461
  • 3
  • 22
  • 44