Need help on Reading from a file

This is a discussion on Need help on Reading from a file within the C++ Programming forums, part of the General Programming Boards category; Ok I am suppose to do this: For research purposes and to better help students, the admissions office of your ...

  1. #1
    Registered User lifeis2evil's Avatar
    Join Date
    Oct 2007
    Posts
    76

    Unhappy Need help on Reading from a file

    Ok I am suppose to do this:
    For research purposes and to better help students, the admissions office of your local university wants to know how well female and male student GPAs for certain courses. Due to confidentiality, the letter code f is used for fimale students and m for male students. Every file entry consists of a letter code followed by a GPA. Each line has one entry. The number of entries in the file is unknown. Write a program that computes and uptputs the average GPA for both females and male students. Format your results to two decimal places.

    That is the question and this is what i have so far in code:
    Code:
    //include section
    #include <iostream>
    #include <conio.h> //for use with getch
    #include <string> //string data types
    #include <fstream> // in and out data
    
    
    using namespace std;
    
    int main ()
    {
    string name,majorname,coursename;
    ifstream inData;
    ofstream outData;
    double f;
    double m;
    double average;
    char gender=' ';
    
    
    inData.open("input.txt") 
    outData.open("outData.txt");
    
    //stuff writting out to screen / displayed
    cout<<"Hello there, What is your name?"<< endl;
    getline(cin,name);
    cout<<"Welcome "<<name<<endl;
    cout<<"Please enter your degree your majoring in."<<endl;
    getline(cin,majorname);
    cout<<"What the name of the course your taking for your major "<<majorname<<" ?"<<endl;
    getline(cin,coursename);
    cout<<"What is your gender? Enter m for male or f for female"<<endl;
    cin>>gender;
    
    inData >> m >> f;
    
    if(m == m)
    cout<<"Your average test score is : " <<m<<endl;
    
    else 
    cout<<"Your average test score is : " <<f<<endl;
    
    
    //Stuff written out to txt file
    outData<<"Person's name is " <<name<<". And there degree major is "<<majorname<<"." 
    " The class course name for there degree major is "<<coursename<< "."<<endl;
    
    
    
    outData.close();
    getch ();
    return 0;
    }

    is there any way to make the calculations in the input.txt file and then read it from the file. Its suppose to add all the m scores and give an average if they answer m and add all the f and give the average it they answer f.

    I'm 100% stuck and have no idea how to do this >_< I've tried it different ways but it's still wrong pleasee helps

    This is the input file http://www.geocities.com/lifeis2evil/input.txt
    in my computer I have it in the same drive as the project. The outData works fine, I just need help with the inData. ..Thank you!!

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    Your code doesn't seem to match the problem statement at all. The problem doesn't mention anything about getting input from the user or worrying about majors and stuff. Are you sure that's not just leftover code from a previous assignment?

    The first step would be to start with an empty program. Add an empty main() function. Then add code to open an input file and verify that it opened (print an error message if the open fails). Once you compiled and tested that and it finds your input file correctly, you can move on to worrying about reading from the file.

    I would start by reading the data from the file at writing it to cout. To read the data from the file you will need two variables, one for the gender and one for the GPA. That's your hint, see if you can get that far.

  3. #3
    Registered User lifeis2evil's Avatar
    Join Date
    Oct 2007
    Posts
    76

    Unhappy

    Quote Originally Posted by Daved View Post
    Your code doesn't seem to match the problem statement at all. The problem doesn't mention anything about getting input from the user or worrying about majors and stuff. Are you sure that's not just leftover code from a previous assignment?

    The first step would be to start with an empty program. Add an empty main() function. Then add code to open an input file and verify that it opened (print an error message if the open fails). Once you compiled and tested that and it finds your input file correctly, you can move on to worrying about reading from the file.

    I would start by reading the data from the file at writing it to cout. To read the data from the file you will need two variables, one for the gender and one for the GPA. That's your hint, see if you can get that far.
    That is part of the work , I am suppose to have:
    o output to the screen.
    o output to file (write to a file)
    o input from the keyboard.
    o input from a file (read from a file)
    o use and declare variables
    o have at least one assignment statement
    o have at least one calculation
    o format your output by using set(w)
    o format your number to 2 decimal places and show .00
    o include a form of selection (i.e. if, if...else, switch)
    o include a form of repetition (i.e. loops)

    .
    double gender;
    double gpa;
    ?

  4. #4
    Registered User lifeis2evil's Avatar
    Join Date
    Oct 2007
    Posts
    76
    it doesnt give me any errors with finding the input file only when i'm trying to use it to find the average and if else section

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    Ok, so even with the other stuff in there, you need to check to see if the input file was opened correctly. You can use inData.is_open() for that.

    Then you need to read in the data. Your current code looks like this:
    Code:
    inData >> m >> f;
    There are two problems with that. First, a line of data has a gender and a GPA. You are reading into m and f. You want the variables you use there to match what you are trying to read in. Since the gender is a char and the GPA is a double, you should probably have a char variable for the gender and a double variable for the GPA. Right?

    So add that code and get it working. You can test that it works by outputting it immediatly to cout (only for testing, you'd remove that output code after you know it works).

    The second problem is that you only read one line. You need to loop while the read is successful. The expression inData >> x evaluates to true if it is successful, so you can put that into the control of your loop. This way you read in each line.

    Once you have those two things working, then you can worry about how you're going to use the data you read in to get the averages.

  6. #6
    Registered User lifeis2evil's Avatar
    Join Date
    Oct 2007
    Posts
    76

    Unhappy

    So something like this or is my code wrong? I know to do somewhat but I have no idea what the code is suppose to look like:

    I am suppose to do a while loop which would open the inData file read each line if its a m and keep looping or if its a f it would open the inData file read 1 line at a time and keep looping for the f right? Then it would need to close the loop and add the average of whichever the person picks whethere m or f

    Code:
    //include section
    #include <iostream>
    #include <conio.h> //for use with getch
    #include <string>  //string data types
    #include <fstream> // in and out data
    
    using namespace std;
    
    
    int main ()
    {
       
        string name,majorname,coursename;
        ifstream inData;
        ofstream outData;
        double gpa;
        double average;
        char gender;
           
        
        inData.open("input.txt");
        outData.open("outData.txt");
        
        //stuff writting out to screen / displayed
        cout<<"Hello there, What is your name?"<< endl;
        getline(cin,name);
        cout<<"Welcome "<<name<<endl;
        cout<<"Please enter your degree your majoring in."<<endl;
        getline(cin,majorname);
        cout<<"What the name of the course your taking for your major "<<majorname<<" ?"<<endl;
        getline(cin,coursename);
        cout<<"What is your gender? Enter m for male or f for female"<<endl;
        cin>>gender;
    
    
    
        
        //Stuff written out to txt file
        outData<<"Person's name is " <<name<<". And there degree major is "<<majorname<<"." 
        " The class course name for there degree major is "<<coursename<< "."<<endl;
    inData >> gender >> gpa;
    
    inData.is_open(); 
    
    while (gender == m)
    {   
       
    }
            if (cout == m)
            
            else
            
               
        
        getch ();
        return 0;
    }

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    Code:
    inData >> gender >> gpa;
    That looks good. The next step I'd suggest is to put that in a loop so that you loop through each line in file. As it is, you are only reading one line.

    Code:
    inData.is_open();
    That does nothing. The point of using is_open() was for you to use the return value to verify that the file is open. You should figure out how to do that.

    Code:
    while (gender == m)
    If you want to test the gender to see if it is m or f, you need to put the character in quotes:
    Code:
    if (gender == 'm') // if gender is male
    Code:
    if (cout == m)
    This and the else below it do nothing. Don't leave extra random stuff in the file. Only put code in there that you know what it is supposed to do and why you have it in there.

    Once you get your loop working so that you are reading in all lines of the file, then you can figure out what to do when gender is 'm' and when it is 'f'. I think maybe the first step would actually be to find the average of all gpas, and ignore the gender. If you can output the average of all gpas, then you can go back and separate the male and female gpas into separate averages.
    Last edited by Daved; 10-19-2007 at 03:58 PM.

  8. #8
    Registered User lifeis2evil's Avatar
    Join Date
    Oct 2007
    Posts
    76

    Unhappy

    Thank you soo much for helping me
    When I run it, it says m is undeclared, but what would I declare it as? double? or is it suppose to be reading that from the file?

    so are you saying something like this? i'm unsure if the looping part is wrong or possibly missing something ?


    Code:
    //include section
    #include <iostream>
    #include <conio.h> //for use with getch
    #include <string>  //string data types
    #include <fstream> // in and out data
    
    using namespace std;
    
    
    int main ()
    {
       
        string name,majorname,coursename;
        ifstream inData;
        ofstream outData;
        double gpa;
        double average;
        char gender;
           
        
        inData.open("input.txt");
        outData.open("outData.txt");
        
        //stuff writting out to screen / displayed
        cout<<"Hello there, What is your name?"<< endl;
        getline(cin,name);
        cout<<"Welcome "<<name<<endl;
        cout<<"Please enter your degree your majoring in."<<endl;
        getline(cin,majorname);
        cout<<"What the name of the course your taking for your major "<<majorname<<" ?"<<endl;
        getline(cin,coursename);
        cout<<"What is your gender? Enter m for male or f for female"<<endl;
        cin>>gender;
    
    
    
        
        //Stuff written out to txt file
        outData<<"Person's name is " <<name<<". And there degree major is "<<majorname<<"." 
        " The class course name for there degree major is "<<coursename<< "."<<endl;
    
    
    
    while (gender == m)
    {   
       
    }
           if (gender == 'm') // if gender is male
            inData >> gender >> gpa;
            
            else  if (gender == 'f') // if gender is female
            inData >> gender >> gpa;
               
        
        getch ();
        return 0;
    }

  9. #9
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,709
    At least you feel like you're getting somewhere.

    Well Daved still had a pretty good suggestion, let's break down the steps we need to take to get there.
    Quote Originally Posted by Daved
    I would start by reading the data from the file at writing it to cout. To read the data from the file you will need two variables, one for the gender and one for the GPA. That's your hint, see if you can get that far.
    I honestly think that if you start out like Daved suggested, then you will be better prepared to finish your homework on your own. Okay, well we know that in order to read a file we need:
    * a stream object that works
    * a place to store the information
    * means to get that information
    * to understand that cout prints to the console (by default)

    Let's not build the whole program at once.

    Getting a stream object to work is actually very easy. For example, with ifstream, all you need to do is open() something. But since opening a file changes the state of the stream, you cannot just assume that the stream is still working; occassionally, people will make typos and you will attempt to open something that isn't there. Gone undetected, this can break the program if you try to read any data. Since open() is an operation that can fail for most streams and break them, the is_open() function was written and standardized to protect you.

    Declaring a variable, I hope, is also easy for you. You just need to make sure that you correctly store the data you received from a source by using the correct types of variables. You also know how cout and the stream insertion operators ( >> and << ) work.

    Collecting all the data from a stream source implies that you also need to loop input operations. Given that you understand the tools you need to use, the task is at least that much simpler. Or parent site, www.cprogramming.com, has a lot of tutorials if you need to relearn a part of the language, like if-else statements or looping.

    All that's left to do after you're correctly reading and writing to the files you need, is to process the data you collected. Try tallying all the scores if someone is a boy. Then tally the scores of boys and girls at the same time. Finally, calculate and print the output.

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    >> When I run it, it says m is undeclared
    Remove that line, it is wrong. You wanted 'm' instead. I just quoted it to indicate that you don't want to do that.

    I would remove this whole piece of code:
    Code:
    while (gender == m)
    {   
       
    }
           if (gender == 'm') // if gender is male
            inData >> gender >> gpa;
            
            else  if (gender == 'f') // if gender is female
            inData >> gender >> gpa;
    Then take this code:
    Code:
    inData >> gender >> gpa;
    and make it into a loop. Don't worry about 'm' or 'f' for now. Just read the data in a loop so that you get all the lines from the file. Remember, you want to loop while the read succeeds (which is while the line of code above succeeds).

  11. #11
    Registered User lifeis2evil's Avatar
    Join Date
    Oct 2007
    Posts
    76

    Unhappy

    a for loop or a while loop or a do while loop?

  12. #12
    Registered User lifeis2evil's Avatar
    Join Date
    Oct 2007
    Posts
    76

    Unhappy

    I really need help on this. I have to present it tomorrow and this is the only part I'm stuck on. can someone please give me the code / help me with it, so that I can make it work and then I can learn it. Please it is really important that I get this to work, I tried going to my prof. in office hours but he wasn't there and half the people I know in that class are lost too because she didn't really teach is this stuff well. Please Help

  13. #13
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,635
    Code:
    char strTemp[4];
    double dTempGPA;
    double nFemaleGPA = 0, nMaleGPA = 0;
    UINT32 nFemaleNum = 0, nMaleNum = 0;
    double* pGenderGPA = NULL;
    UINT32* pGenderNum = NULL;
    
    FILE* f = fopen("indata.txt", "r");
    if (f == NULL); // Failed to open file - figure out why and toss our an error or something
    for(;;)
    {
    	fread(temp, 4, 1, f);
    	if ( feof(f) ) break;
    	if (temp[0] == 'm')
    	{
    		pGenderGPA = &nMaleGPA;
    		pGenderNum = &nMaleNum;
    	}
    	else if (temp[0] == 'f')
    	{
    		pGenderGPA = &nFemaleGPA;
    		pGenderNum = &nFemaleNum;
    	}
    	else ASSERT(FALSE); // There was unexpected data read from the input file
    	fread(temp, 4, 1, f);
    	*pGenderGPA += atod(temp);
    	(*pGenderNum)++;
    }
    fclose(f);
    
    nFemaleGPA /= nFemaleNum; // Average GPA
    nMaleGPA /= nMaleNum; // Average GPA
    char ToDisplay[1000];
    vsprintf(ToDisplay, "Average female GPA: &#37;0.3f.\nAverage male GPA: %0.3f.", nFemaleGPA, nMaleGPA);
    cout << ToDisplay;
    ...Something like that. If I understood it all correctly.
    I didn't test the code - but you should be able to do that yourself.
    Last edited by Elysia; 10-21-2007 at 10:46 PM.

  14. #14
    Registered User lifeis2evil's Avatar
    Join Date
    Oct 2007
    Posts
    76
    i don't know why but almost none of that code makes sense to me. I am using Dev-C++ compiler program

  15. #15
    Registered User lifeis2evil's Avatar
    Join Date
    Oct 2007
    Posts
    76
    Code:
    //include section
    #include <iostream>
    #include <conio.h> //for use with getch
    #include <string>  //string data types
    #include <fstream> // in and out data
    
    using namespace std;
    
    
    int main ()
    {
       
        string name,majorname,coursename;
        ifstream inData;
        ofstream outData;
        double gpa;
        double average;
        char gender;
        char m;
     m = 0;
           
        
        inData.open("input.txt");
        outData.open("outData.txt");
        
        //stuff writting out to screen / displayed
        cout<<"Hello there, What is your name?"<< endl;
        getline(cin,name);
        cout<<"Welcome "<<name<<endl;
        cout<<"Please enter your degree your majoring in."<<endl;
        getline(cin,majorname);
        cout<<"What the name of the course your taking for your major "<<majorname<<" ?"<<endl;
        getline(cin,coursename);
        cout<<"What is your gender? Enter m for male or f for female"<<endl;
        cin>>gender;
    
    
    
        
        //Stuff written out to txt file
        outData<<"Person's name is " <<name<<". And there degree major is "<<majorname<<"." 
        " The class course name for there degree major is "<<coursename<< "."<<endl;
    
    inData >> gender >> gpa;
    
    while (m <= 1)
    {
          inData >> gender >> gpa;
                       }    
      
        getch ();
        return 0;
    }

Page 1 of 8 12345678 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 09:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21