Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
C++ help
#1
Something I need help with is importing data. I can't really grasp how to do it very well.
The assignment I have to do is

 Spoiler
He gave us a notepad file called Ex11Data.txt that has all of that info in it. Now I could do the assignment without importing the data (by just entering it all manually into the program itself), but I won't learn anything by doing it that way. If anyone could explain the best way to import the data that would be great.

Another thing I have trouble understanding is how to make use of object oriented programming. I guess I just need to practice more with it. The last time I had a class on it was a few months ago and I kind of forgot it =P. I know an object is something that is kind of universal to the program and can be moved around, but I'm having a bit of trouble creating one properly and making good use of it/knowing when to use it.
Reply
#2
If you need to deal with data from an external source, you'll need the fstream class. This class allows you to use the ifstream and ofstream functions - the first to read files and the other to write to them.

Is that enough info to get you started? Tongue
Reply
#3
We didn't HAVE to import data for this, but I wanted to try it. This is the code I wrote without importing data.

Code:
#include <iostream>
using namespace std;
int main()
{
    char student;
    double grade;
    double femalegrades=0;
    double malegrades=0;
    int femalecount=0;
    int malecount=0;
    double femaleaverage=0;
    double maleaverage=0;

    cout<<"Enter in the gender of the student then the grade"<<endl;
    cout<<"Enter end to stop"<<endl;
    cin>>student>>grade;

    if (student == 'm')
    {
        malegrades+=grade;
        malecount++;
    }
    if (student == 'f')
    {
        femalegrades+=grade;
        femalecount++;
    }


    while (student == 'f' || student == 'm')
    {
          cin>>student>>grade;

          if (student == 'm')
          {
          malegrades+=grade;
          malecount++;
          }
          if (student == 'f')
          {
          femalegrades+=grade;
          femalecount++;
          }
    }

    maleaverage=malegrades/malecount;
    femaleaverage=femalegrades/femalecount;

    cout<<"Sum of the male grades : "<<malegrades<<endl;
    cout<<"Sum of the female grades : "<<femalegrades<<endl;
    cout<<"Male count : "<<malecount<<endl;
    cout<<"Female count : "<<femalecount<<endl;
    cout<<"Male GPA average : "<<maleaverage<<endl;
    cout<<"Female GPA average : "<<femaleaverage<<endl;

    system("pause");
    return 0;
}

runs just fine but you have to type all of the stuff manually (dunno if that's what he wanted to be honest).

and I have NO IDEA what ifstream and ofstream are lmao. I'm so noob at this ="(

This is the next assignment I'm working on now
 Spoiler

man I suck at functions too -_-"
What I think I'm going to do for the random addition problems is make a randomizer spit out 10 numbers, and store those 10 numbers into 10 variables. Then just do like number1+number2 = answer.

could someone explain how to call out random numbers from an array? That would definitely be useful

Edit- I'm having trouble getting my randomizer to give me different numbers. This is me playing around with my randomizer, but it's spitting out the same number for randnum1 and randnum2
Code:
#include <iostream>
using namespace std;
int random();
int main()
{
    int randnum1, randnum2;

    randnum1 =  random();
    randnum2 =  random();

    cout<<randnum1<<endl;
    cout<<randnum2<<endl;

    system("pause");
    return 0;
}

int random()
{
    int number;
    srand ( time(NULL) );
    number=(rand()%11);
    return (number);
}
Reply
#4
Not going to do it for you, but I'll show you how it would be done in C:
 Spoiler
Reply
#5
Eos, it's \r\n, not \n\r. At any rate, check the newlines in the file.

An alternate option if you're trying to optimize disk usage would be to use strtok after reading the whole file into memory. Then with the string returned from strtok, use sscanf. Eos's way can read a file of up to whatever your file system can handle. Mine trades memory consumption for speed.

To increase clarity, you can also use a struct.

Code:
struct Scores
{
    int count;
    double total;
}

Then in the function.

Code:
int main(void)
{
    struct Scores Men;
    struct Scores Women;

    ...
}

Then in the loop:

Code:
            switch ( gender )
            {
                case 'm':
                    Men.scores += score;
                    Men.count++;
                    break;
                case 'f':
                    Women.scores += score;
                    Women.count++;
                    break;
            }
Reply
#6
Fiel Wrote:Eos, it's \r\n, not \n\r. At any rate, check the newlines in the file.
Depends on your OS.
Windows likes to do 0d0a, *nixes are more explicit and tend towards just \n but I'm used to \n\r from TTY outputs.

Compiled and worked successfully on my sample which is what matters Wink
Reply
#7
I like how simplified your code is Fiel. I'm trying to learn to write as little code as I can and what you wrote is pretty nice. Is struct and object programming the same thing? It looks pretty similar.
Reply
#8
Structures are precursors to OOP.
Classes are structures with events and functions, more or less.

You could do the same thing he was proposing with an enum as well.
Reply
#9
Oh ok I got it. Objects and functions are definitely my weak point at the moment. I should get plenty of practice (i think) with the other assignments I have to do. That randomizer is being a peach though lol.
Reply
#10
Eosian Wrote:Windows likes to do 0d0a, *nixes are more explicit and tend towards just \n but I'm used to \n\r from TTY outputs.

Compiled and worked successfully on my sample which is what matters Wink

Code:
int main(void)
{
    short theRealMansWay;

    theRealMansWay = ntoh16("\n\r");

    return 0;
}
Reply
#11
OOP is meant to follow natural language by letting code mimic the real world.

An object is any thing that you can dream up. Think of a notebook for example. A notebook is an object. An object is merely a thing with which you can perform actions on it. So you can read a notebook, write in the notebook, and update a notebook. These actions are of a "can" relationship with the notebook (you CAN read a notebook [Notebook.Read()], you CAN write in it [Notebook.Write()], you CAN update it [Notebook.Update()]). All "can" relationships are functions within the object.

Then you have "has a" relationships. So a notebook has a number of pages, it has a current page opened, it has a spiral binding, and it has a front cover. All of these "has a" relationships are variables within the object (int, short, string). In the struct shown above, each Score struct "has a" count and "has a" total.

The idea of OOP is data hiding. Ideally, the only way you should interact with an object is by sending commands to the object and never change its variables directly.

An object defines an abstract concept. For example, in the object definition you define what every notebook should look like. But the certain one on your table is one instance of that object. Every notebook you come across is a different instance of that object. Then you can change the state of each notebook by sending commands to its instance. Like in the real world, you can update the notebook on your desk without updating every single notebook in the universe.

Then you have "is a" relationships. This defines inheritance. So a diary is a kind of notebook. A daily planner is a kind of notebook. Inheritance specifies a more explicit type of your object. You can then inherit all of the functions from Notebook (read, write, update) into the diary object, but also include specific functions to make working with diaries easier (getCurrentDate(), WriteJournalEntry(), setCurrentMood())

If you still feel a bit lost, check out the Java introduction to OOP. Pretty much everything there will translate to any OOP language you encounter. The names might be slightly different, though.

EDIT: Nail down Objects ASAP. If you don't, you will be brutally destroyed by the time you start learning about OOP patterns.
Reply
#12
In this case, you could have the object Student, with 2 properties - sex and gpa.

Of course, you can add other variables if you wanted (age, height, etc.) but in this case those 2 are all we really know.

Then when you read the input file, for each line you create a new instance (like creating a new variable) and set its properties according to the data.


I'm less familiar with C++ but in Java, when you create an object, you can implement default "interfaces" which means you give the object a certain set of functions that behave in a pre-specified manner. Such as print() returning a string describing the object, or compareTo(object) telling you which has a larger value. Once you implemented these functions you can treat your new object just like the primitive types (int, char, double, etc.) in your code, sticking them in lists, adding/subtracting them, printing, etc.

Eg. if you had sex(char) in your Student class, returning true if sex==char and false if sex!=char, you could write if(student.sex('m')) malegpa += student.gpa(); else femalegpa += student.gpa(); Then again, that's not really clear code - you'd more likely want to write getSex() which returns a char (m or f) and have if(student.getSex() == 'm').
Reply
#13
Could someone help me out with my randomizer? I can't get it to spit out 10 different numbers and store those in 10 variables. The one I wrote just spit out 1 number and stored it in both randnums.
Reply
#14
why do you have 10 variables? I hope you're putting it into an array.

Post it.
Reply
#15
Its up in the 3rd post. I gotta make 5 different random math problems. I would store it in an array but I couldn't figure out how to make a loop that not only kept spitting out new numbers, but also stored those numbers into new variables.

5 problems is 10 variables.
Reply
#16
ahaha, very cute problem with your rand function

Code:
int random()
{
    int number;
    [b]srand ( time(NULL) );[/b] // <--- THIS IS THE PROBLEM
    number=(rand()%11);
    return (number);
}

Your code runs so blindingly fast in C that all of it completes in less than a second. So you're seeding the PRNG with the same number for every function call. Call srand() in the main function before you call your own rand() wrapper.
Reply
#17
LoL sweet. I'm glad it was an easy fix. I can't test it out right now since I'm not home (I'm on my cell phone).

The code I wrote was something I was using as a template sorta. Just to get a randomizer spittin out numbers and being able to store them. Making an array and making the math problems should be easy now.
Reply
#18
First, convert your main() into a function like update_gpa(float gpa, int* gender_count, float* total_gpa). Basically, all this function does is updating the scores. Once you did that, recode your main() to call this function.

Once that's done, you will need to use a file stream reader (which I totally forgot the syntax for) and I think there's a function readline to read in a line in the file. As you can see, line[0] is the gender, and the rest is a float. Substring will do the trick here.

Your main() will be something like this:
for each line in the file, gender = line[0], gpa = convert to float(line[1..n])
if gender is m, pass in the gpa, the male total, the male gpa total into update_gpa
otherwise, pass in the gpa, the female total, the female total gpa into update_gpa

IMO, that's clean modular programming.

To make this OOP, firstly, you need a class calls GpaManager, which has 4 vars, male_total, female_total, male_total_gpa, female_total_gpa and perhaps 2 constants, MALE and FEMALE.

Then, you would need a public function calls update_gpa(char gender, &float gpa) and

protected function update_female_gpa(&float gpa)
protected function update_male_gpa(&float gpa)

Note that you're only going to read the GPA, so it's OK to pass the reference.

In update_gpa, it does the if statement and calls the male/female version of the function.

you can also do a toString() function for the class GpaManager, so that you can do something like cout << GpaManager.

That's pretty much does all the GPA logics.

Now, you can do something like a StdinGpaManager, which reads the data in from the std input and/or a FileGpaManager, which reads the data in from the file.
Reply
#19
wow.... maybe trying to call the information from a file wasn't a good idea lol. It seems way more complicated than I thought it would be. I thought I could just do something like

call(insert file path here);

and that would be it. I guess I was wrong eh?

Well here is the code I have going for the rand function. I'm surprised it was so easy to write.
Code:
#include <iostream>
using namespace std;
int random();
int main()
{
    int array[10];
    int x;

    srand ( time(NULL) );

    for (x=0; x<10; x++){
        array[x]=random();
        cout<<array[x]<<endl;
        }

    system("pause");
    return 0;
}

int random()
{
    int number;

    number=(rand()%11);
    return (number);
}
gonna keep playing with it of course, but I got it spitting out random numbers and storing it into my array.
Reply
#20
A quick search on google for "c++ read from file" yields something like this http://www.cplusplus.com/forum/beginner/8388/.

Given your capability to write code above, I dont see how hard it is to merge it with the 3rd post. There're minimal changes to your code to achieve what you wanted.

Tho, rather than mashing everything together into the main function, it is advisable to split it out to multiple. Like it or not, what you written are very primitive, and most likely wont be seeing it ever in the real world environment. Another thing I tend to see is that newbie programmers tend to let hell loose in their code. Try to maintain some disciplines with your code and it'll reward you greatly when you have to maintain it later. You may not know it, but even the best of us has written shitty code, and at later time, when we looked back at it, the reactions were "wtp?? i wrote this?" or "wtp is going on in here?"

That's why I suggested you tried modifying your code to something a bit more modular and more resusable by having a new function that handles the GPA logic. There is not much additional work in doing what I suggested either. As for OOP, well, take your time with that.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)