Reading string from a file and storing the characters separately

Discussion in 'iOS Programming' started by abichaz, Mar 4, 2010.

  1. abichaz macrumors newbie

    Mar 4, 2010
    I am building a game similar to mastermind for the iPhone and I am needed to compare two strings character by character. I need to choose a string from the database and compare it with the string entered by the player.

    I have tried the following but it does not seem to work. Can you please help me.

    //create file handle
    	NSFileHandle *file;
    	file = [NSFileHandle fileHandleForReadingAtPath:@"4db.txt"];
    	//read data into file in NSData format
    	NSData *filedata;
    	filedata = [file readDataToEndOfFile];
    	//convert NSData to NSString
    	NSString *string;
    	string = [[NSString alloc] initWithData:filedata encoding:NSASCIIStringEncoding]; 
    	//convert from string to array
    	NSArray *lines = [string componentsSeparatedByString:@"\n"]; 
    	//take one of the string and store it in sword
    	NSString *sword = [lines objectAtIndex:0];
    	//convert string to char
    	const char *word = [sword UTF8String];
    	sec[0] = word[0];
    	sec[1] = word[1];
    	sec[2] = word[2];
    	sec[3] = word[3];
    I am now assuming sec contains the characters of the string that I read from the file. It does not seem to work. Kindly help. Any other efficient method would b great if you can suggest.

    Thanks in advance
  2. xUKHCx Administrator emeritus


    Jan 15, 2006
    The Kop
    I've added [code] tags to make the code a lot easier to read.

    To do this either type [code]...your code here...[/code]

    Or press the code button [​IMG] when making your post.

  3. chown33 macrumors 604

    Aug 9, 2009
    Sailing beyond the sunset
    First, show the definition of the sec array.

    Second, explain exactly what happens (or doesn't happen) when things don't work. In other words, explain how you know it doesn't work.

    Third, describe exactly what is contained in the file "4db.txt". In particular, what is the first line, since that's the only text you're using.

    Other than the fact that you're not checking for any errors, I see nothing obviously wrong with what you're doing. But without seeing how the sec array is defined, and how you're using it when it doesn't work, it's impossible to say anything definitive: you simply haven't provided enough information.

Share This Page