Thread: Program crashing when replacing newline character

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    12

    Program crashing when replacing newline character

    Hey guys,

    I have a simple function that reads info from a file and stores in into arrays. An example of the file is shown below:

    1 2 Text
    3 4 More Text
    5 6 Even More Text
    1000
    So basically, the program scans in the first number, second number and text until it reaches the sentinel 1000 and it stops.

    Here's the code

    Code:
    i=0;
    	
    	fscanf(workout, "%d", &set[i]);
    	while (set[i] != 1000) {
    		fscanf(workout, "%d ", &increment[i]);
    		fgets(drill_name[i], SIZE, workout);
    		drill_name[i][strlen(drill_name[i])-1]='\0';
    		i++;
    		fscanf(workout, "%d", &set[i]);
    	}
    When I run this program it crashes with error:
    Program received signal: “EXC_BAD_ACCESS”.

    However, I've found out that when I take out the line of code:
    Code:
    drill_name[i][strlen(drill_name[i])-1]='\0';
    The program works fine. But I need this code there to remove the newline character after each text. I have some similar functions in my program that have the same line of code and work fine, so what's going wrong here?

    Thanks

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
           i=0;
    	
    	do {
    		fscanf(workout, "%d %d %s", &set[i]; &increment[i], &drill_name[i]);
    		drill_name[i][strlen(drill_name[i])-1]='\0';
    		i++;
    	}while (set[i-1] != 1000);

    Give that a try. You can't mix fscanf() and fgets, on the same line of text. Generally, you can use fscanf(), (as here), OR you can get the whole line with fgets(), and then take out the parts you need into the variables, with sscanf().

    It's not uncommon for input with fscanf() to take some tweaking to work.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    12
    I figured it out. Turns out my array had some random junk in it that was messing up the file opening so it worked sometimes but not others.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Hi, Quiz C program Assignment updated
    By Eman in forum C Programming
    Replies: 19
    Last Post: 11-22-2009, 04:50 PM
  2. Function call is crashing program
    By Shaun32887 in forum C++ Programming
    Replies: 4
    Last Post: 07-17-2008, 03:18 AM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. Character stack ADT program
    By alice in forum C Programming
    Replies: 1
    Last Post: 07-05-2004, 04:30 AM
  5. comparing int to newline character
    By RedZippo in forum C++ Programming
    Replies: 5
    Last Post: 05-13-2004, 06:37 PM