Gulshan
Gulshan

Reputation: 3761

How to take the input from user in console or file with ease in c#?

I am a C++ user and now trying to use c#.

In c++ taking input from the user was fun (just >>) and supported all the types. So was for the files. But in c# it is too complex, as I can take only strings. Then I have to manipulate it for later use.

And if I want to take multiple inputs in same line separated by whitespaces, it become more complex as I have to go for string splitting. Then conversion...

May be it is for error handling and safe code. But I am disappointed with C# anyway.

You are all expert guys here. Is there any easy way?

Upvotes: 1

Views: 1006

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273199

As already answered, C# does not support this. No overloading of << or >> for streams at all and while there is a TextWriter.WriteLine(" ",...) there is no corresponding TextReader.ReadLine() with variable parameter list.

I'll take a guess at Why: the whitespace-spepareted data format dat cin understands simply isn't used a lot anymore.

Upvotes: 1

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247919

As far as I'm aware, you have to do it the hard way. (On the bright side though, the hard way is simpler than it'd be in C++ ;))

Console.OpenStandardInput() does give you the input stream, so it can be treated the same as files, but you'll have to do the string splitting yourself if you need that. Of course, C# has a nice Regex library that may help here.

T.TryParse (where T is int, float, whichever type you want to read) should let you convert the string to those types.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062630

Ultimately, it wouldn't take much to wrap it - you'd just need to buffer the current line and read off inputs in your desired format. But IMO, a little split/TryParse etc rarely hurts.

I'm not 100% sure of the expected formats that >> accepts, but I doubt it would be hard to do something similar. I'm not volunteering to write it, though ;-p

Upvotes: 2

Related Questions