rifter1818 Posted April 11, 2005 Posted April 11, 2005 Im working with C# and i need an input method that can ignore whitespace (from a file) something like c++'s ifstream would be great... inputing floats, strings and ints. Really soon would be nice too as the time i have to finish is measured in hours, thanks. Quote
HJB417 Posted April 12, 2005 Posted April 12, 2005 there isn't a port of the ifstream class in .net but hopefully this collection of methods can help you achieve similar functionality. public static bool IsFloatingPoint(string value) { return (value == null) ? false : System.Text.RegularExpressions.Regex.IsMatch(value, @"^\s*[-+]?(\d*(\.)?)\d+\s*$"); } public static bool IsInteger(string value) { return (value == null) ? false : System.Text.RegularExpressions.Regex.IsMatch(value, @"^\s*[-+]?\d+\s*$"); } public static string ReadWord(System.IO.TextReader stream) { AdvanceToNextWord(stream); System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(stream.Peek() == -1) return null; while(stream.Peek() != -1) { char value = Convert.ToChar(stream.Read()); if(char.IsWhiteSpace(value)) break; sb.Append(value); } return sb.ToString(); } private static void AdvanceToNextWord(System.IO.TextReader stream) { while((stream.Peek() != -1) && char.IsWhiteSpace(Convert.ToChar(stream.Peek()))) stream.Read(); } static void Main(string[] args) { using(System.IO.StreamReader sr = System.IO.File.OpenText(@"C:\somefile.txt")) { while(true) { string value = ReadWord(sr); if(value == null) return; string type = "string"; if(IsFloatingPoint(value)) type = "floating point"; if(IsInteger(value)) type = "integer"; Console.WriteLine("{0}: {1}", type, value); } } } Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.