Thread: Newbie homework help

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    3

    Newbie homework help

    Hi. Let me preface this by saying I am not asking anyone to do my homework for me, just looking for someone to help steer me in the right direction. I will post the description of the assignment and then post the code I have thus far. I know my code doesn't work(it crashes right away) but hopefully it will let you see how I am approaching this program and then you can feel free to tell me how awful my program is:-). Seriously though, I welcome any constructive criticism and again, I am not asking anyone to do my work for me but hopefully you can tell me which parts of my program are working and which I need to examine a little more closely. Thanks in advance.

    Code:
    Title: Lab 14
    Description: Simple File Input and Output
    Points: 100
    Source Code File Name: <G-Number>-lab14.c
    Subject Key: CS133U Lab 14 Submission
    Standard Input:
             Input file name as command line argument argv[1]
             Input file contains three floating values and an operator, e.g.
                   2.5
                   3.5
                   4.5
                   +
    
    Introduction
    ------------
            This assignment extends input and output to file streams.  You have used printf and scanf
            in earlier assignments, and in this lab you should use the more general fscanf and fprintf 
            functions to read and write to files.
    
            Your program will accept the name of an input file from the command line, specifically argv[1].
            If you are using DevC++ then you will need to set the name of the input file in the Execute/Parameters
            dialog box.  You may use any valid file name you wish, but the file must have the format shown in the
            "Standard Input" section, i.e. three float values followed by a char value (a total of four lines
            in the file).  Keep in mind that when I grade your program I will use my own file name, so do not
            hard-code a file name into your code - use the name specified in argv[1].
    
            Your program will read the numbers and the operator from the input file, and then display the sum of 
            the values.  Please note that while you must read the operator character from the file, you do NOT
            need to interpret the operator character.  You can simply add the three values no matter what operation
            is specified.
    
            After displaying the sum of the three values your program will write "Hello World!" to an output
            file called "lab14.output".
    
    Instructions
    ============
            1. Copy the 'hdrm.c' file to 'lab14.c' and use it as the starting point for your code.  Update the
               comments in the file to reflect this assignment.
    
            2. The command line argument argv[1] contains the input file name.  Open this file for input.
    
            3. Read the 4 lines of the input file (3 float values and 1 char value) and close the file.
    
            4. Display the values you read
    
            5. Display the sum of the 3 float values with a precision of 3 decimal places
    
            6. Open the file 'lab14.output' for output
    
            7. Write the string "Hello World!" to the output file 'lab14.output' and close the output file
    
    
    Submission
    ==========
    Your source code file must be named <G-Number>-lab14.c, and must be an ASCII text file. 
    You should submit just the source code file - no executable code! 
    I will compile and execute your source code on my grading system and return a 
    feedback file to you in a few days.
    
    You will submit your <G-Number>-lab14.c source code file using Blackboard, 
    as discussed in class. Submit your code to the Lab 4 assignment dropbox.
    
    Standard Input
    ==============
    13:27:16> cat lab14.input
    2.5
    3.5
    4.5
    +
    
    Sample Output
    =============
    
    13:27:19> lab14.exe lab14.input
    Read the following values from 'lab14.input':
            2.500
            3.500
            4.500
    
    2.500 + 3.500 + 4.500 = 10.500
    
    Press ENTER to end
    [normal program end]
    
    13:27:38> cat lab14.output
    Hello World!
    13:27:43>
    And here is my code so far
    Code:
    /**
    	@page lab14 Simple Input and Output
    	This program accepts the name of an input file, reads numbers and operators
    	from the input file and then dispalys the sum of the numbers.
    	@section Authors
    	@author Justin Foss
    	<p>
    	@section Contributors
    	- N/A
    	*/
    	/**
    	@file G03426789.c
    	@version 1.0
    	@details
    	Demonstrate input and output using fscanf and fprintf
    	*/
    	#include <stdio.h>
    	#include <stdlib.h>
    	
    
        
    
    void main_end();                                
    
    
    
    int main(const int argc, const char **argv)
    {
        float val_A, val_B, val_C, sum; //Float variable
        char ch_A, str[30];             //Character and String variable
        FILE *fp;                       //File pointer
        
        //Prompt to enter filename
        printf("Enter filename: \n");  
        
        //Opens and reads file specified in argv[1]
        fp = fopen(argv[1], "r");       
        
        //Scans values from specified file
        fscanf(fp, "%f %f %f %c", &val_A, &val_B, &val_C, &ch_A);
    
        //Stores filename to string variable
        str[30] = fp;  
        
        //Calculates the sum of the three values in specified file
        sum = val_A + val_B + val_C;
        
        //Displays error message if file does not exist
        if (fp == NULL)
          printf("Not a valid file\n");
        
        //Displays values and the sum of the values from the specified file
        else if (fp != NULL){
             printf("Read the following values from '%s'\n", str);
             printf("\t%.3f\n \t%.3f\n \t%.3f\n", val_A, val_B, val_C);
             printf("\n%.3f + %.3f + %.3f = %.3f", val_A, val_B, val_C, sum);
              
             
    }
      //Closes file
      fclose(fp);
    }
                                   
                                                   
    
    void main_end()
    {
          printf("Press ENTER to end");
          fgetc(stdin);                                
          printf("[normal program end]\n");
          exit(0);                                     
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
        //Stores filename to string variable
        str[30] = fp;
    I'm surprised this even compiles. If it does, it should give you a warning of some sort.

    Code:
        //Prompt to enter filename
        printf("Enter filename: \n");  
        
        //Opens and reads file specified in argv[1]
        fp = fopen(argv[1], "r");
    You ask for a filename, but you do not read anything in from the user. I suspect from the problem description that you shouldn't even be ASKING for the filename. You may want to, as a help to debug, print out the filename given in argv[1] - that way, you can see that you are not trying to open a file with a different name than you think.

    Code:
        //Displays error message if file does not exist
        if (fp == NULL)
          printf("Not a valid file\n");
    This if-statement should move up to before you are USING fp to read from a file, and you should exit(1) from the program, since you can not feasibly continue with the rest of the prorgram if you couldn't open the file as if it is NULL, it WILL crash your program - it may well be what is happening, but the first code-snippet I commented on will also quite possibly cause a crash.

    Code:
    void main_end()
    {
          printf("Press ENTER to end");
          fgetc(stdin);                                
          printf("[normal program end]\n");
          exit(0);                                     
    }
    This function isn't being called.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Apr 2009
    Posts
    3
    Thanks for the help so far. I am starting to close in on this but I am still having some trouble. I've changed some things around and can get the program to run as intended when I hard code in a file name, but I am still having problems when I try to use a file name specified in argv[1]. I know it seems like I am just continuing to ask questions until someone gives me the correct code, but I assure you I am only using the forum as a last resort and am only wanting guidance, not the answer. Thanks again in advance.

    Code:
    /**
    	@page lab14 Simple Input and Output
    	This program accepts the name of an input file, reads numbers and operators
    	from the input file and then dispalys the sum of the numbers.
    	@section Authors
    	@author Justin Foss
    	<p>
    	@section Contributors
    	- N/A
    	*/
    	/**
    	@file G03426789.c
    	@version 1.0
    	@details
    	Demonstrate input and output using fscanf and fprintf
    	*/
    	#include <stdio.h>
    	#include <stdlib.h>
    	
    
        
    
    void main_end();                                
    
    
    
    int main(const int argc, const char **argv)
    {
        float val_A, val_B, val_C, sum; //Float variable
        char ch_A;                      //Character variable
        FILE *fp;                       //File pointer
        
        fp = argv[1];
        
         //Displays error message if file does not exist
        if (fp == NULL){
          printf("Not a valid file\n");
          exit(1);
           }
       
       //Scans values from specified file
       else if (fp != NULL){
        fp = fopen(argv[1], "r"); 
        fscanf(fp, "%f %f %f %c", &val_A, &val_B, &val_C, &ch_A);
        sum = val_A + val_B + val_C;
             printf("Read the following values from %s\n", argv[1]);
             printf("\t%.3f\n \t%.3f\n \t%.3f\n", val_A, val_B, val_C);
             printf("\n%.3f + %.3f + %.3f = %.3f", val_A, val_B, val_C, sum);
              
             
    }
      //Closes file
      fclose(fp);
      fgetc(stdin);
    }
                                   
                                                   
    void main_end()
    
    {
          printf("Press ENTER to end");
          fgetc(stdin);                                
          printf("[normal program end]\n");
          exit(0);                                     
    }

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Can you PLEASE enable warnings in your compiler:
    Code:
        fp = argv[1];
    makes about as much sense as
    Fish underpants vacuum-cleaner
    does as a sentence.

    fp is a file-pointer, argv[1] is a pointer to char. They do not match, and certainly setting fp to point to a char pointer is not a good plan for executing correctly. fp needs to point to a FILE object. You get a file-object by calling fopen(). In that respect, your original code was much closer.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. newbie homework help please
    By phnominon in forum C Programming
    Replies: 2
    Last Post: 11-11-2006, 09:32 PM
  2. Newbie: Homework Help
    By soheel in forum C++ Programming
    Replies: 6
    Last Post: 10-04-2005, 10:59 AM
  3. Urgent homework help for NEWBIE
    By Kazasan in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2004, 04:23 PM
  4. Homework
    By kermi3 in forum C Programming
    Replies: 0
    Last Post: 09-10-2001, 01:26 PM