Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

Posted

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...