Sign in to follow this  
0x0539

[.net] C#'s istream equivalent

Recommended Posts

Hey I have a text file with ASCII encoded numbers in it (integers) and chars, and I would like to read them into variables similar to C++. What would be the C# equivalent to this C++ code? I want to keep it simple, and not have to read a line and parse it for the values. Data file:
1 2 3 a
Code:
int x, y, z;
char a;
ifstream text("file.txt", ifstream::in);
text >> x >> y >> z >> a;
ifstream.close();

Share this post


Link to post
Share on other sites
int x, y, z; char a;
using(var stream = new StreamReader(File.OpenRead("file.txt"))) {
var parts = stream.ReadLine.Split(new []{' '});
x = int.Parse(parts[0]);
y = int.Parse(parts[1]);
z = int.Parse(parts[2]);
a = parts[3][0];
}


Share this post


Link to post
Share on other sites
Quote:
Original post by 0x0539
Wow, slap in the face lol. Thanks for the enthusiasm though. Now anyone have any ideas how to do this without parsing?

Sure, use an XML file format and serialization.

Share this post


Link to post
Share on other sites
Quote:
Original post by 0x0539
Wow, slap in the face lol. Thanks for the enthusiasm though. Now anyone have any ideas how to do this without parsing?


Well, being as istream parses and hides all the bloat away, your options are the two posted by Washu, or inherit from StreamReader to add ReadInt* etc functionality, either way, there's nothing OOTB that will do a one to one like istream.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this