Skip to main content
GameDev.net gamedev.net
🔒 Locked

file input

Started by nb2 Mar 4, 2009 at 4:27 PM 1 replies 1k views
Original Post
nb2
nb2
hi all, i'm currently having some difficulty in coding something that shouldn't be so hard. part of the program that i am working on is supposed to read in a number from a file (which would basically be the last line input to it) and add 1 to it. here is the code i am using right now. it might look like i am attempting to do things in an odd way, but i have tried so many different ways before this. i am working in c++.net

int pagenum = 1;
						
//default if no previous values
	StreamReader* read_pnum = new StreamReader(File::Open("pnum.txt", FileMode::OpenOrCreate));	//open stream to read page number file
	if(read_pnum->Peek()>=0)
	{
		String* line;
		while(line = read_pnum->ReadLine())
		{
			if(Int64::Parse(line)){
				pagenum = Int64::Parse(line);
				pagenum++;
			}
		}
	}
	read_pnum->Close();
	StreamWriter* write_pnum = File::AppendText("pnum.txt");
	write_pnum->WriteLine(" ");
	write_pnum->WriteLine(url);
	write_pnum->Write(pagenum);
	write_pnum->Close();

so basically, what this code is supposed to do is if the file is empty, output a web page address to a file followed by the number 1 (which is supposed to be the page number). if there are other pages stored in the file, then get the last number in the file, add 1 to it, and output the page address and the new page number to a file. Unfortunately, nothing I have tried in this block works; it won't convert my page number to an integer i don't think. Any help with this would be greatly appreciated!! Thanks
Evil Steve
Evil Steve
This looks pretty suspect to me:
String* line;
// Snip
if(Int64::Parse(line)){

I suspect that Parse() expects the object pointed to be already constructed (Otherwise it'll have to take a reference to a pointer to allocate space for you, which seems a bit wrong). Shouldn't that be:
String line;
// Snip
if(Int64::Parse(&line)){

?

Note that I've never used .NET before, only "normal" C++.
Zahlman
Zahlman
if(Int64::Parse(line)){


You cannot "check" this way if the text actually represented a number. The result of Int64::Parse(line) is the number, if there is a number. If there is no number, it will throw an exception. The only way that 'if' would fail is if the line held the text "0", producing the parsed number 0. Of course, your input file has other lines with stuff besides the number, so you'll get the exception first.

To get around this, you could use a try/catch block, but that doesn't really express your intent - you're expecting it to fail on every line but one. Instead, use Int64::TryParse to "look before you leap".

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.