Murtan 317 Practically a Master Poster

And if you do the struct thing, the call to Totaller could take 2 structs, one for the totals and one for the new data to add to the totals.

Sample struct, but you can add or remove fields as appropriate

struct Payinfo {
    float gross;
    float federaltax;
    float statetax;
    float ssitax;
    float hours;
    float payrate;
    float deferred;
    float reghrs;
    float ovthrs;
    float netpay;
}
Murtan 317 Practically a Master Poster

You probably can put it into 2 different functions. You could probably make it work if you tried hard enough. But was the point to make the two 20 argument functions work or to make the code work?

I don't know if you saw the suggestion, but the creation of a struct that you fill with the arguments and then pass a pointer to the struct is actually a MUCH better implementation than all of the individual parameters.

The struct allows you to set the parameters by name. So to verify that the right data is in the right place is just verifying that the source data is correct for the target member. Validation of the function calls with 20 arguments involves looking at the prototype and parameter counting to make sure you get the data in the right position in the list.

The struct makes it easy to pass the same arguments on to another function if that is required.

If you REALLY want to do the 20 argument functions and have more than one, you might want to make a convention for the declaration and calling of the functions where you put each argument on its own line in the source file. It helps with the argument counting and other validation if the parameter list is clear. It would also help to have a logical organization for the order that the parameters appear.

sample of layout, but I still don't recommend it:


       
Murtan 317 Practically a Master Poster

So you want the loop to keep running while the xPos is different or the yPos is different. You wrote while the xPos is different AND the yPos is different. The loop needs to run while either doesn't match.

while((board.getgXPos() != board.getXPos()) || (board.getgYPos() != board.getYPos()))
SHWOO commented: Helpful! +3
Murtan 317 Practically a Master Poster

Can you run it yet?

What does it do?

Murtan 317 Practically a Master Poster

If you're not going to use sortField, go ahead and remove it.

PS- ddanbe is right

In my sample program, the sort submenu looks like this:

sortExit = false;
                do{
                   char sortCommand;
                   cout << "1: Student ID" << endl;
                   cout << "2: Quiz 1 Grade" << endl;
                   cout << "3: Quiz 2 Grade" << endl;
                   cout << "4: Exam 1 Grade" << endl;
                   cout << "5: Exam 2 Grade" << endl;
                   cout << "6: Assignment 1 Grade" << endl;
                   cout << "7: Assignment 2 Grade" << endl;
                   cout << "8: Assignment 3 Grade" << endl;
                   cout << "9: Return to main menu" << endl;
                   cout << endl;
                   cout << "Enter field to be sorted(1-8): ";
                   cin >> sortCommand;
                   
                   switch (sortCommand){ 
                          case '1':
                               for (int ii = 0; ii < Num_Students; ii++)
                                   scores[ii] = grades[ii].ID;
                               sortList(scores, Num_Students);
                               showList(scores, Num_Students);
                               break;
                          // 
                          // Skipping cases for 2-8 here
                          // 
                          case '9':
                               sortExit = true;
                               break;
                          default:
                               cout << "Invalid Command" << endl;
                   }
                }while( !sortExit );
ddanbe commented: respect is mutually, this is a hard one +3
Murtan 317 Practically a Master Poster

Your code:

//Sort IDs or grades into a column.
           case '3':
                do{
                   cout << "1: Student ID" << endl;
                   cout << "2: Quiz 1 Grade" << endl;
                   cout << "3: Quiz 2 Grade" << endl;
                   cout << "4: Exam 1 Grade" << endl;
                   cout << "5: Exam 2 Grade" << endl;
                   cout << "6: Assignment 1 Grade" << endl;
                   cout << "7: Assignment 2 Grade" << endl;
                   cout << "8: Assignment 3 Grade" << endl;
                   cout << endl;
                   cout << "Enter field to be sorted(0-7): ";
                   cin >> sortWhat;
                   
                   switch (sortWhat){ 
                          case '1':
                               sortField(Num_Students[], int num, sortWhat);
                               showList(grades[].ID, Num_Students);
                               break;
                          case '2':
                               int q1scores[65];
                               for (int ii = 0; ii < Num_Students; i++)
                               q1scores[ii] = grades[ii].q1;
                               break;

I moved and renamed the q1scores array (I was getting warnings).
I presumed an alternate version of sortField named sortList that expects an array of integers and a count. It sorts the array.

//Sort IDs or grades into a column.
           case '3':
                do{
                   cout << "1: Student ID" << endl;
                   cout << "2: Quiz 1 Grade" << endl;
                   cout << "3: Quiz 2 Grade" << endl;
                   cout << "4: Exam 1 Grade" << endl;
                   cout << "5: Exam 2 Grade" << endl;
                   cout << "6: Assignment 1 Grade" << endl;
                   cout << "7: Assignment 2 Grade" << endl;
                   cout << "8: Assignment 3 Grade" << endl;
                   cout << endl;
                   cout << "Enter field to be sorted(0-7): ";
                   cin >> sortWhat;
                   int scores[Num_grades];
                   
                   switch (sortWhat){ 
                          case '1':
                               for (int ii = …
Murtan 317 Practically a Master Poster

Ok, I'm curious, what compiler are you using? (I'm still seeing lots of compile errors.)

I found another basic problem. Inside your main() you declare char sortField which hides the function int sortField(students grades[], int num, string sortThis) This may be related to your current issue.

How are the sub-selections under '3' sort grades supposed to work?

If I select 1, should the output just be a sorted list of IDs? or should the entire grades array be sorted by ID and then output?

If I select 2, should I just see a sorted list of quiz 1 grades or all of the records ordered by the quiz 1 grade?

Murtan 317 Practically a Master Poster

I agree with ninwa, the function you have doesn't make much sense.

void addressType::print_add(string str, string Cit, string St, int Z)
{
	cout<<"Address: "<<str<<endl;
	cout<< Cit <<","<<St<<endl;
	cout<<"Zip: "<<Z<<endl;

	return ;

}

The function asks you pass in all of the address data when the address data is already in the class. (Though your sample doesn't show how the address data got in there.)

You could write the print method as shown by ninwa, or if you prefer your output format:

void addressType::print_add()
{
	cout << "Address: " << St_address << endl;
	cout << city << "," << state << endl;
	cout << "Zip: " << Zip << endl;
}

Additional comments:

#1 If you have a function with a void return type, the return statement at the end of the function is not necessary.

#2 It is a good idea to establish naming conventions for your classes and members. The one that stood out the most to me as not matching were the names of the data members. You have a leading capital letter on 2 of them and leading lower-case on the other 2. It probably should be one way or the other, but not both.

Murtan 317 Practically a Master Poster

It's the programmers responsibility to ensure the target buffer is sufficiently large enough to hold the maximum possible output size.

I think lint (or something like it) might catch it, but I'm not sure.

Murtan 317 Practically a Master Poster

note that POINTS actually contains 3 full instances of the POINT (whatever that happens to be) while EDGE only contains 2 pointers to POINT.

This code isn't quite right:

POINTS some_points;
EDGE an_edge;
an_edge.p1 = some_points.pts[0];

This will work:

POINTS some_points;
EDGE an_edge;
an_edge.p1 = &some_points.pts[0];
// or
an_edge.p1 = some_points.pts;
// or if you wanted to point to something other than the first element in the array:
an_edge.p1 = &some_points.pts[1];
// or
an_edge.p1 = &some_points.pts[2];

In the case where p1 points to pts[0], yes it is true that there are 2 more data items following the one you're pointing to, but if p1 was pointing to pts[2] there are not. It would all be a matter of handling p1 as if it only points to one value (specifically ignore or refuse to use anything other than the one value is points to.)

Note that the assignment to p1 (or p2) does NOT copy the data in the POINT, it only copies the address of where the POINT was located in memory.

Murtan 317 Practically a Master Poster

It may not be very efficient, but this creates an output file with the one string in it:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FileCreationTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            String test = "This is some sample data\n";
            FileStream fh = File.OpenWrite("targetfile.txt");
            fh.Write(Encoding.ASCII.GetBytes(test), 0, Encoding.ASCII.GetByteCount(test));
            fh.Close();
        }
    }
}
Murtan 317 Practically a Master Poster

You also have a basic misunderstanding of arrays of structures.

For example in your sort case, you have this in one of the subcases:

sortList(grades[].q1, Num_Students);
    showList(grades[].q1, Num_Students);

You seem to be under the impression that you can generate an array of quiz one scores with grades[].q1 what you have is a syntax error. If you want an integer array containing the quiz one scores, you're going to have to make it.

int q1scores[65];
    for (int ii = 0; ii < Num_Students; ii++)
        q1scores[ii] = grades[ii].q1;

This might come closer to what you're looking for, but I'm not sure.

If you want to be able to sort the entire grades array by different fields in the structure, you would normally write one sort that takes a comparison function (which tells you which record of two would come first) and the helper comparison functions for the different fields you want to sort by.

Your swap inside your bubble sort is also problematic:

if(grades[k].ID > grades[k + 1].ID){
                              temp = grades[k].ID;
                              grades[k] = grades[k + 1];
                              grades[k +1].ID = temp;
                              swap = true;

This saves the ID from structure [k], copies all of the fields from [k+1] to [k] (id, q1, q2, e1, e2, assg1, assg2, assg3), then sets the ID in [k+1] from the saved ID. You lost all of the scores from record [k].

Murtan 317 Practically a Master Poster

I had to massage it a little to get it to compile under VCPP Express.

I think your key problem is that you have 2 copies of the array arrayGrid one declared globally that never gets initialized and one declared in main that is never used.

gamePlay() calls displayGrid() passing the global copy of arrayGrid.

my compiler didn't like the char arrayGrid[21][21] version of the array. It was complaining about some of the initializers. (I guessed that the default char implementation was signed. So I changed all of the declarations to unsigned arrayGrid[21][21] and moved the initilized one to global space.)

When I run it I see this when I select battle:

╔═╤═╤═╤═╤═╤═╤═╤═╤═╤═╗
║ │ │ │ │ │ │ │ │ │ ║
╟─┼─┼─┼─┼─┼─┼─┼─┼─┼─╢
║ │ │ │ │ │ │ │ │ │ ║
╟─┼─┼─┼─┼─┼─┼─┼─┼─┼─╢
║ │ │ │ │ │ │ │ │ │ ║
╟─┼─┼─┼─┼─┼─┼─┼─┼─┼─╢
║ │ │ │ │ │ │ │ │ │ ║
╟─┼─┼─┼─┼─┼─┼─┼─┼─┼─╢
║ │ │ │ │ │ │ │ │ │ ║
╟─┼─┼─┼─┼─┼─┼─┼─┼─┼─╢
║ │ │ │ │ │ │ │ │ │ ║
╟─┼─┼─┼─┼─┼─┼─┼─┼─┼─╢
║ │ │ │ │ │ │ │ │ │ ║
╟─┼─┼─┼─┼─┼─┼─┼─┼─┼─╢
║ │ │ │ │ │ │ │ │ │ ║
╟─┼─┼─┼─┼─┼─┼─┼─┼─┼─╢
║ │ │ │ │ │ │ │ │ │ ║
╟─┼─┼─┼─┼─┼─┼─┼─┼─┼─╢
║ │ │ │ │ │ │ │ │ │ ║
╚═╧═╧═╧═╧═╧═╧═╧═╧═╧═╝

Is that the grid?

PS- you didn't include color.h so I commented out the RED and NORMAL and the using namespace Petter. For some reason the Sleep didn't resolve either so I macro'd them away. I also had to stub out shiledLeft(), move(), direction() and stats().

Murtan 317 Practically a Master Poster

Is this a problem:

cout << "Enter field to be sorted(0-7): ";
                   cin >> sortWhat;
                   
                   switch (sortThis){ 
                          case '1':

You're getting the input into sortWhat and then switching on sortThis.

Murtan 317 Practically a Master Poster

You moved the lines too far out...(sigh)

import random
#list of words the computer will be picking
word_list = ['python', 'jumble', 'easy', 'difficult', 'answer', 'tracer', 'muffin']

print "I'm picking one of the " , len(word_list), "words from a secret list"
random_word = random.choice(word_list)
print "Computer has selected secret word", len(random_word), "letters."

guess_count = 0
correct_guess = ""
wrong_guess = ""
previous = ""
correct = random_word

while guess_count<5:
      guess_count+=1

      while True:    
          guess=raw_input("\nguess one letter ")
          guess = guess.strip().lower()

          if len(guess) >1:
              print "Please enter only one letter."
          elif guess in previous:
              print guess, ("has already been guessed ")
              guess_count-=1
          else:
              break


      if guess in correct:
         print guess, "\nyes"
         correct_guess += guess
         previous += guess
      else:
         print guess, "\nno"
         wrong_guess += guess
      previous += guess

print correct_guess
print wrong_guess

print len(correct_guess), "correct guesses and", len(wrong_guess), "incorrect"

## guessing the word

print "Guess the word"
guess = raw_input ("\nYour guess:")
guess = guess.lower()
while (guess != correct) and (guess !=""):
    
   if guess != correct:
        print "Incorrect..\n"
   break
   print "Thanks for playing."     
   raw_input("\n\nPress the enter key to exit.")   
   

if guess == correct:
   print "That's it! You guessed it!\n"

print "Thanks for playing."
raw_input("\n\nPress the enter key to exit.")
Murtan 317 Practically a Master Poster

Can you use functions...you're having a hard time keeping the indenting right.

lines 31-38 should be out one indent...they need to be 'inside' the while guess_count < 5 but not 'inside' the while True

The "er no" is coming from line 36 but you're not supposed to get there until you've passed all the input tests.

I actually wrote a 'get me a letter' function and I call it from the main in my test app.

def getLetterGuess(previous):
    # Remind the user of the previous guesses if any
    if len(previous) > 0:
        print "You have already guessed:", ','.join(previous)
    # loop until we get a valid guess
    while True:
        lguess = raw_input("Guess a letter: ").strip().lower()
        if len(lguess) != 1:
            print "Enter only one character"
        elif not lguess.isalpha():
            print lguess,"is not a letter, please try again"
        elif lguess in previous:
            print "You have already guessed",lguess
        else:
            break
        print
    return lguess

Then I use it from the main like this:

# Take the Letter Guesses
for gidx in xrange(5):
    guess = getLetterGuess(previous)
    if guess in random_word:
        print "Yes,", guess, "is in the word"
        correct_guess += guess
    else:
        print "Sorry,", guess, "is not in the word"
        wrong_guess += guess
    previous += guess
Murtan 317 Practically a Master Poster

I did some initial review, and I was able to load the library and call hgeCreate using ctypes:

Run this from a directory with the hge.dll in it, I was in the hge181 directory.

from ctypes import *
hge = windll.hge
hgeCreate = hge.hgeCreate
hgeCreate.restype = c_void_p

hge = hgeCreate(0x180)

But from there, it would seem ctypes does not support making calls into c++ classes, and that appears to be how you interface to the rest of hge. (hgeCreate returns a pointer to an instance of the class)

Prahaai commented: Very concise. It solves some of my problems. +4
Murtan 317 Practically a Master Poster

When I put the while loop where it was supposed to go, I got the following from running it:

I'm picking one of the  7 words from a secret list
Computer has selected secret word 6 letters.

guess one letter er
Please enter only one letter.

guess one letter sd
Please enter only one letter.

guess one letter ght
Please enter only one letter.

guess one letter e
e is not correct

guess one letter rt
Please enter only one letter.

guess one letter r
r is not correct

guess one letter tr
Please enter only one letter.

guess one letter t
t is not correct

It looks like it is working to me.

while guess_count< 5:
    guess_count+=1

    while True:
        guess=raw_input("\nguess one letter ")
        guess = guess.strip().lower()

        if len(guess) >1:
           print "Please enter only one letter."
        elif guess in previous:
           print guess, ("has already been guessed ")
        else:
           break

    if guess in correct:
Murtan 317 Practically a Master Poster

Name search: You start at the head and while there are still entries on the list, you compare the names. If they match, you found it. (if the list is still in alphabetical order, you can stop when you find a name > than the one you're looking for.)

ID search: You start at the head and while there are still entries on the list, you compare the IDs. If they match, you found it.

Once you have found it, you need to be careful about the updates. It is usually best form to remove the one you found, update it and re-add it. (Because if the field that specifies the list order changes, you need to re-position the record in the list.)

Murtan 317 Practically a Master Poster

In my test app, I didn't limit them to entering one letter, but I validated what they typed and complained if it was more than one character.

You could replace the raw_input and the first if test with a while loop:

while True:
    guess = raw_input("\nguess one letter ")
    guess = guess.strip().lower()
    if len(guess) > 1:
        print "Please enter only one letter"
   elif guess in previous:
        print guess, "has already been guessed "
   else:
        break

If you do, remember to change the elif guess in correct: to if guess in correct:

Murtan 317 Practically a Master Poster

Please use code tags when posting code, preferably the language-specific version so we get syntax highlighting. It makes the code MUCH easier to read.

If you want the linked list to be ordered by last name, the convention is to put the record in the list where it belongs.

If the first record added is for "James Smith" then it is the only record. If we now want to add a record for "Bill Wilson", it should be added after "James Smith". If we then add a record for "Carol Fisher" if goes before "James Smith". Repeat as additional records are added and the list will always be sorted by last name.

So the code ends up looking something like:

// preinitialize the new record's next to null
newstudent -> next = null;

student_list * prev = null;
student_list * curr = head;
// while there are more records to look at on the list
while (curr != null)
{
   // should the new record come before the 'current' record in the list?
   if (strcmp(newstudent -> Last_Name, curr -> Last_Name) < 0)
   {
      newstudent -> next = curr;
      break
   }
   prev = curr;
   curr = prev -> next;
}

if (prev == null)
   head = newstudent
else
   prev -> next = newstudent
Salem commented: Better copy/paste the "please use tags" phrase to a hot key, you need it a lot at DW +24
Murtan 317 Practically a Master Poster

You didn't post your whole source file, so the line numbers don't line up...

student.cpp: In member function `Student Student::operator+(const Course&)':
student.cpp:67: error: no matching function for call to `Student::Student()'
student.h:21: note: candidates are: Student::Student(const Student&)
student.cpp:15: note: Student::Student(std::string, Date)

The above error indicates that your operator+ implementation is creating a new instance of Student using the default (no-parameter) constructor, but that you have not defined the default constructor.

student.cpp:68: error: passing `const Course' as `this' argument of `int Course::getNumberOfCridet()' discards qualifiers
student.cpp:69: error: expected `)' before '{' token
student.cpp:80: error: expected primary-expression before '}' token
student.cpp:80: error: expected `;' before '}' token

I think this last set is based on line 69. I suspect you have an 'if' statement that doesn't have enough parens. Something like the following would generate that type of error:

if (x == (average(b, c)) {

PS- I agree with Narue, bumping your post doesn't help.

Note: these forums are not INSTANT. Generally, if you have a concise and clear question your reply will be rapid, but don't expect instant responses. I believe we're all donating our time here, to even look at your questions...appreciate the help you do get.

Murtan 317 Practically a Master Poster

you're still missing the elif guess in correct: before the print guess,"is correct" I'm hoping its just the broken code tag that caused it, or you lost your indentation.

Murtan 317 Practically a Master Poster
def isWhole(num):
    return num == int(num)

Works pretty well, but can fail for numbers that are really close to whole:

Test code and output

for ii in xrange(1,20):
    f = float('3.'+'9'*ii)
    print ii, f, isWhole(f)
    
1 3.9 False
2 3.99 False
3 3.999 False
4 3.9999 False
5 3.99999 False
6 3.999999 False
7 3.9999999 False
8 3.99999999 False
9 3.999999999 False
10 3.9999999999 False
11 3.99999999999 False
12 4.0 False
13 4.0 False
14 4.0 False
15 4.0 False
16 4.0 True
17 4.0 True
18 4.0 True
19 4.0 True
Murtan 317 Practically a Master Poster

you're getting stuck on the while loop:

while(strstr(arr,"RECORD DEFINITIONS")==NULL)
{
fgets(arr,120,fp);
printf("\n%s",arr);
}

Nothing in the main while(!feof(fp)) ever resets the value in arr. So when you get to the second record's data you print 'INTO THE RECORDS NOW' but don't ever actually read any data because arr still contains 'RECORD DEFINITIONS'

When you fix that, you're going to have a problem when you're reading the last record in the file (if your file is like the file you attached). The last record does not have a 'RECORD DEFINITIONS' after it to close the while loop. You should probably either add a test for eof() to the while, or test for eof() inside the while and use break to stop.

The other way I've written similar parsers in the past is to use a 'parse state' variable. For your example, your parse states would be something like LOOKING_FOR_RECORD, LOOKING_FOR_DETAIL, IN_DETAIL

So pseudo code for the parser would look something like:

#define LOOKING_FOR_RECORD 1
#define LOOKING_FOR_DETAIL 2
#define IN_DETAIL 3
int pstate = LOOKING_FOR_RECORD;
while(!feof(fp))
{
    fgets(buff,MAX,fp);
    
    switch (pstate)
    {
        case LOOKING_FOR_RECORD:
            if (strstr(buff, "RECORD NAME:") != NULL)
            {
                // Do Record Name handling here
                pstate = LOOKING_FOR_DETAIL;
            }
            break;
        case LOOKING_FOR_DETAIL:
            if (strstr(buff, "DESCRIPTION") != NULL)
                pstate = IN_DETAIL;
            break;
        case IN_DETAIL:
            // from your sample file, you could also stop IN_DETAIL when you encounter an empty line
            if (strstr(buff, "RECORD DEFINITIONS") != NULL)
                pstate = LOOKING_FOR_RECORD;
            else
            {
                // Do Detail Record Handling Here …
Murtan 317 Practically a Master Poster

yes, and be careful of using the get* methods in outputdata, its not necessary, just reference the members.

Murtan 317 Practically a Master Poster

From what I'm reading of the posts and assignment, you should remove the for loop from inputData() and add a for loop to main to call inputData for all three TMoney members of the array money.

TMoney money[3];
for (int jj = 0; jj < 3; jj++)
    money[jj].inputData();

The first data entered will be in money[0], the second in money[1] and the third in money[2].

You're supposed to print the second set?

money[1].outputData();
Murtan 317 Practically a Master Poster

That still has the range bug in it.

There is no game[9]

the first winning row should be game[0], game[1], game[2]

Also, when you call state() from main(), the value for first (which is the player to move) has already been updated to the player for the next move, but state() is looking to see if that player won. You should call state() with the player that just filled a square.

Murtan 317 Practically a Master Poster

I wanted to see the body of state(), not the prototype.
State decides who won and was the source of a lot of your bugs earlier...I want to see how you have re-coded it.

Murtan 317 Practically a Master Poster

Could you post the new version of state()? (and any other code related to checking for wins?)

Murtan 317 Practically a Master Poster

I tried to explain about indenting before...

Your while loop that starts on line 13 only contains line 14 and line 15. Line 16 will not be executed until the while is complete.

You lost an elif statement between lines 18 and 19...

The while loop used to go through line 26 in previous versions of the code.

The while loop starting on line 33 will keep looping until you get the right guess or enter a blank line, but the loop doesn't contain code to prompt for another guess.

line 34 is incrementing tries. Where did tries come from, do we use it anywhere?

The tests for incorrect on lines 35 and 37 can be performed as a single if guess != correct:

Murtan 317 Practically a Master Poster

is state() supposed to detect winners?

First of all, it does not always return a value.

Secondly the expression game[1]&&game[2]&&game[3]==play does not test positions 1, 2 and 3 for the value play. I think you wanted game[1] == play && game[2] == play && game[3] == play Third, when you declare the board with game[9] the indexes are 0 through 8. There is no 9.

Murtan 317 Practically a Master Poster

If you had the words in a list, you could just iterate over the code you have, something like:

# wordsToFind = ["plane", "red", "yellow", "king"]
# how they got into the list is up to you.

print "\nNow searching horizontal rows\n"
for word in wordsToFind:
    found = i = 0
    while not found and i < len(arr):
        if 'plane' in arr[i]:
            found = 1
        else:
            i=i+1
    if found:
        print word, 'found in horizontal row', i+1
    else:
        print word, 'not found horizontally'

#put the array transform here:

print "\nNow searching vertical columns\n"
for word in wordsToFind:
    found = i = 0
    while not found and i < len(newarr):
        if 'plane' in newarr[i]:
            found = 1
        else:
            i=i+1

    if found:
        print word, 'found in vertical column', i+1
    else:
        print word, 'not found vertically'

But even that example almost has enough repeated code to ask for a function. Have you already covered functions, could you break some of this up into one?

Murtan 317 Practically a Master Poster

That looks pretty close to what I expected.

You can get rid of the variables in main for name, age, gpa.

I tend to declare only one thing per line, but its a coding convention / personal preference issue. I also tend (in c++) to declare most variables close to the point of use:

int main(){
  student x;
  ofstream ofile("student.dat",fstream::app);
 
  //Fill the file with student records
  while(!cin.eof()){
    x.read();
    if(!cin.eof()){
      x.writefile(ofile);
    }
  }
  ofile.close();

  float sum=0;
  int i=0;  
  ifstream infile("student.dat");
  cout<<"______List of Students in student.dat_____"<<endl;
  while(!infile.eof()){   
    x.readfile(infile);
    if(!infile.eof()){
      x.show();
      sum += x.getgpa(); 
      i++;
   }  
  }
  infile.close();
  
 cout << "\nThe avg. GPA is:" << sum/i << endl;
  
return 0;
}

Does it run? Is the output acceptable?

Review the assignment requirements, did your application do everything on the list?

Murtan 317 Practically a Master Poster

The code:

int main ()
{

int N, throwaway, cards[N], suit[N], compCards[N], compSuit[N];

will declare arrays of length N (but at the time of the array construction, N is either zero or undefined). The arrays will NOT be resized when the user enters a value for N later in the function.

So if you later then fill the arrays up to the new value of N, you are overwriting memory that doesn't belong to you.

Murtan 317 Practically a Master Poster

We generally don't do 'instant' solutions or links to them here.

We like to help those who help themselves. If you've put some effort into a solution, but don't understand why you get the results you do, or the errors you're getting, post the errors or results (preferably with code -- in code tags --) and we will try to help.

Murtan 317 Practically a Master Poster

definenum is NOT a constructor, it is a method.

The code void definenum(int num) {} is like me walking up to you and handing you something, but not telling you what to do with it; eventually, you'll throw it away.

When you expand the code to void definenum(int in_num){num=in_num;} you told the class what to do with the something. "When someone calls definenum, take what they gave you and save it in num, throwing away any previous value."

Murtan 317 Practically a Master Poster

I'm not sure what you mean by a 'sexy' solution. I think any solution that works is sexy! (grin)

I would have indented the x.writefile call to show that it is under the if and I would probably have used braces too.

// If we haven't reached the end of the input, write the latest record
if (!cin.eof())
{
    x.writefile(ofile);
}

You're still refusing to use the members of the student class to do the work!

Why should main read the data when student defines readfile?

Weren't you supposed to display the data you read? maybe you could call something....oh, what about show?

I think there may have been another method defined to help with the gpa calculation...hmm...

Note for future homework: if the teacher assigns you to write a method, you probably need to call it for the assignment. If not, re-evaluate how you're doing the work, maybe you're missing something. (In any case, I would call all of my methods at least once or twice for testing, I hate it when the teacher finds a bug because I didn't bother to test.)

Murtan 317 Practically a Master Poster

At least part of the problem is in your last set of code...

The tempptr was null, so you allocated and initialized it, but tempptr was just a copy of the pointer from current[target[i]] you made no effort to set the original array entry to the newly allocated item.

Also (I'm actually presuming this is a copy/paste error) the call to the function to recurse calls a function of a different name. (In the function CreateList , it calls CreateRhs )

I can think of other ways to write CreateList, but what you have appears to work. Given a preference, I would have written CreateList something like:

item ** CreateList(int arrayLength, int * maxArray)
{
    int ii;
    int mymax;
    item ** rval;

    if (arrayLength < 1)
        return null;
    mymax = maxArray[0] + 1;
    rval = (item **)malloc( mymax * sizeof(item *));
    for (ii = 0; ii < mymax; ii++)
    {
        rval[ii] = (item *)CreateList(arrayLength - 1, maxArray + 1);
    }
    return rval;
}

This makes an extra recursion to initialze the item pointers to null, but it made the code slightly easier to read. (Feel free to add a test and eliminate the last recursion level.)

I also didn't like doing the cast in rval[ii] = (item *)CreateList but the return type was not compatible with the array type. In order to do that assignment without the cast, we would need to create a union type for the list pointer. The union would either point …

Murtan 317 Practically a Master Poster

The constructor did exactly what you asked it to (as all software should.)

numgetter()
{num=0;}

Defines the constructor to initialize the num to zero.

Murtan 317 Practically a Master Poster

For the double posting of the last student, add a if (!cin.eof()) in front of the x.writefile(ofile)

Ok, so you're opening and closing the infile. Nice start, why don't you read from it until it runs out of data. (Hint it should look a lot like the read from the console until it ran out of data, but use different methods.)

Murtan 317 Practically a Master Poster

The current database search uses where qdate = #" + DateTime.Now.ToString("dd-MMM-yyyy") + "#" which limits the search to only find records for the given date.

You could extend that to have a 'morning', 'afternoon' and 'evening/night' questions using time...

The only other was to implement it would be to somehow get the information as to whether or not the current user has already seen a particular question. (Maybe you could keep a last date/question index for each user?)

If the last question date was today's date, then select the next index question (if any).

Note that the database would need to have a field to establish the order that questions would be presented during the day.

Also note that some entity must be populating the database with questions for future dates so that when the date arrives there is a question available. The entity would have to support adding more than one question for a given date, potentially including an order in which the questions were to be presented.

Now you put some effort into the problem if you want me to post any more, the "I just can't think of anything" is all worn out.

Murtan 317 Practically a Master Poster

For more help with the int vs char for the array implementation, it would help to have a better idea of how the board will be used.

Murtan 317 Practically a Master Poster

Another common option is to leave the board in a single dimensional array. Depending on how you interface to the board, it has advantages and disadvantages.

For example, a 3 x 3 board would use 9 elements in an array. The first 3 would be the first row (or first column depending on your preference) the next 3 would be the second row and the last 3 would be the third and final row.

// ptr is just a char * in my class
void Board::create()
{
    ptr = new char [ width * height ];

    // filling the cells with numbers (I don't know why)
    int k = 1;
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j<height;j++)
        {
            ptr[i * width + j] = k++;
        }
    }
}
Murtan 317 Practically a Master Poster

Then modify the sample code he gave you. Programming is an adventure, TRY something and see what it does (especially on simple things like this).

If you try something and it doesn't do what you want, either modify it and try again, or post it here with a 'it does ___, but I wanted ___' or a 'Why does this code do ____ I thought it would do ___' type of question.

Murtan 317 Practically a Master Poster

Please be more specific with your question..."When I run the program, I'm seeing ____. I tried ____ but it didn't solve it." or something along that line.

Does the code compile?

Does the program run?

Does it do what it is supposed to do?

Murtan 317 Practically a Master Poster

The error I posted was from the command-line compiler.

I'm running:

python --version
Python 2.5.2

The error message was generated with:

python foo.py

where foo.py contained the code you had posted.

The line:

print guess, "has already been guessed ")

does have a syntax error...what's that last closing paren ')' for?

Murtan 317 Practically a Master Poster

ok, you are aware the indentation is CRITICAL in python applications?

In this first case, only one line is executed 10 times and the output is 11 lines long:

for ii in xrange(10):
    print "Apple"
print "Pear"

In this second case, two lines are executed 10 times and the output is 20 lines long, the only difference is whitespace at the start of a line:

for ii in xrange(10):
    print "Apple"
    print "Pear"

I picked up the code from your message and saved it into foo.py
I ran python foo.py and got the following message:

File "foo.py", line 3
    word_list = ['python', 'jumble', 'easy', 'difficult', 'answer', 'tracer', 'muffin']
    ^
IndentationError: unexpected indent

Note that it says the problem is on line 3 and is pointing at the w in word_list. Somehow, you have added a leading space to all of the lines in your code except the import and the first comment.

Take out the leading spaces for top-level lines.

You also have blatant indentation problems with the lines numbered 25 and 29 in your last post. They need to be at the same indentation as the lines before them, but they are obviously not.

Once you fix this indentation so you can compile, you have caused a logic problem by un-indenting code that needs to be part of the while guess_count < 5: loop.

Be patient, go carefully and read the compiler messages. Indent the code …

Murtan 317 Practically a Master Poster

The code item = raw_input("\nYou chose: ") prompts the user with "You chose: " and waits for the user to type characters and press return. All of the characters typed (including the return) will be in the string that is returned. In this case, you stored it in item.

It is fairly common to get rid of the extra whitespace by calling .strip() on the item or the input. For example: item = item.strip() .

Then you can compare what the user typed against the available options:

item = raw_input("You chose: ")
item = item.strip()
if item == "1":
    # they chose 1
elif item == "2":
    # they chose 2
elif item == "3":
    # they chose 3
else:
    # they chose something else

Now modify your code and try something. If you're still having problems, post your new code (using code tags) and describe what works, what doesn't and what help you would like. (More effort on your part will tend to get more help from us.)

Murtan 317 Practically a Master Poster

I apologize, when I read the first line of your original post "To transpose, use zip(*L) where L is a list of tuples, like this", I read it as 'this is the way you should do it' rather than 'another way you could do it'. So I wanted to understand why it was the 'way it should be done'.

As an alternative to the OP's method it makes perfect sense.