Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

No, that really isn't what they mean. What MandrewP was saying was that the type cast doesn't change the type of the original variable; it just returns a copy of it's value, changed to the new type. for example, if you have

double a = 17.23;
int b;

b = (int) a;

Then a itself is still a double ; it hasn't changed at all. Only the value passed to b was cast to the new type.

As for the actual problem with the int=>char conversion, you are still getting part of it backwards: you need to cast the value to the type it is being copied into, not the type it is already.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int a, choice;
    char b, choice2;
    cout << "Would you like to print the ASCII Table first? (Y/N)"<<endl;
    cin >> choice2;
    if(choice2=='y' || choice2=='Y')
    {
        for(int i = 0x21; i <= 0x7E; i += 6)
        {
            cout << setw(6) << static_cast<char>(i) << " = " << setw(3) << i;
            cout << setw(6) << right << static_cast<char>(i + 1) << " = " << setw(3) << i + 1;
            cout << setw(6) << right << static_cast<char>(i + 2) << " = " << setw(3) << i + 2;
            cout << setw(6) << right << static_cast<char>(i + 3) << " = " << setw(3) << i + 3;
            if ((i + 4) < 0x7f)
            {
                cout << setw(6) << right << static_cast<char>(i + 4) << …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Assuming I'm understanding this correctly, what you need to do is combine a regular for() loop conditional with the test for the end of the loop as you have it above:

for (int i = 0; (i < iterations) && (p != currentlist.end()); i++)
{
  // code goes here
}

The reason you need both is for the case where the list is shorter than the number of iterations.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Without seeing the code for your main() function, my guess is that you are using soemthing like

cin >> ch;

to read in the character where the player chooses an option, correct? If so, you will want to clear the input buffer using cin.ignore() immediately after that. What is happening is that the newline after the character is still in the buffer, and you need to clear it before you can read in a new line.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You forgot to include the first argument of the report() function ( numItems ).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What is happening, what problems are occurring? As it is now, the program won't actually do anything, as you never call report() .

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I believe that the problem arises from using counter1 as both the loop index and the counter for the number of times the extra number appears. Try the following code instead:

void printInts ( int randomArray[], int size, int& extra )
{
    int counter;
    for ( counter = 0; counter < size-1; counter++ )
    {
        cout<<setw(30)<<" Random number "<<(counter + 1)<<" generated "<<randomArray[counter]<<endl;
    }
    cout << " \n ";

    extra = randomArray[size - 1];

    cout <<setw(40)<<" The extra random number is: "<< extra << "\n" <<endl;


    int counter1 = 0;

    for ( counter = 0; counter < size - 1; counter++ )
    {
        if ( randomArray[counter] == extra )
        {
            counter1++;
        }
    }
    cout << setw(38) << " The extra number occured " << counter1 << " times " << endl;
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Since you need both a largest value and a smallest value, you will want to declare two variables to hold the two results. Assign the value of n1 to both of them, then substitute ' largest ' for the n1 in your comparisons. This will get you the largest value, just as it did before. Now do the same with the ' smallest ' variable, just reversing the comparison (that is, use greater than rather than less than).

#include<iostream>
using namespace std;

int main()
{
    int n1,n2,n3,n4,n5;
    int largest, smallest;

    cout << "input number1\n";
    cin  >> n1;
    cout << "input number2\n";
    cin  >> n2;
    cout << "input number3\n";
    cin  >> n3;
    cout << "input number4\n";
    cin  >> n4;
    cout << "input number5\n";
    cin  >> n5;

    largest = smallest = n1;

    if(largest < n2)
        largest = n2;
    if(largest < n3)
        largest = n3;
    if(largest < n4)
        largest = n4;
    if(largest < n5)
        largest = n5;

    // TODO: the same thing as above, except replacing 
    // 'largest' with 'smallest' and '<' with '>'
   

    cout << "The largest number is" << largest <<endl;
    cout << "The smallest number is" << smallest <<endl;  
 
return 0;
}

If you have studied arrays, there is a good way to simplify the code using an array instead of having separate variables named n1 , n2 , n3 , etc. Experiment with it a little, and you should find something useful.

As a final note, I have to ask you to write out full words rather …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What seems to be the problem with it? It looks as if it should do what you want, but we need to know what problem you are having in order to help solve it.

Also, please put your code examples in CODE tags in the future. The forum software does not retain indentation by default, so without the code tags, you lose the code's formatting, making it difficult to read clearly.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oops. I've updated my code changes since then. Sorry.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You need to have an index on the monthNames[] array, otherwise what it will return is the pointer (address) of the array rather than the value.

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main ()

{
    double avgRain = 0;
    double rainSum = 0;
    int count = 0;
    int monthlyTotals[12];
    string monthNames[] = {"January","Febuary","March","April","May","June","July","August","September","October","November","December"};
    cout << "Please enter the amount of rainfall for each month, and press enter after each: " << endl;
    for (count = 0; count < 12; count++)
    {
        cout << setw(9) << left << monthNames[count] << " : ";
        cin >> monthlyTotals[count];
    }

    for (count = 0; count < 12; count++)
        rainSum += monthlyTotals[count];

    avgRain = rainSum / 12;


    cout << "Output : " << endl;
    for (count = 0; count < 12; count++)
    {
        cout << setw(9) << left << monthNames[count]
             << setw(3) << right << monthlyTotals[count] << endl;
    }

    cout << rainSum << " is the total rainfall for the year\n" << avgRain << " is the average for the year.\n";
    return 0;
}

Note the use of the setw() manipulator, which gives better control over the spacing than the tab character does. You will need to #include <iomanip> in order to use the manipulators, however. Note also the change in the index conditionals, such that the count variable goes from 0 to 11, rather than 0 to 12. The way it was originally, it was causing a segfault when it reached 12 and overran the arrays.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You'll want to add a check for file.good() after the first getline() in each iteration, or better still, set up a loop and check each one:

void FileInput()
{

    ifstream file ("test1.csv"); 
    
    while ( file.good() ) 
    {
        string value[7];
        for (int i = 0; i < 6; i++)
        {
            getline ( file,value[i], ',');
            if (file.eof() || file fail())
                break;
        }
        getline ( file,value[6]);   

        if (file.good())
        {
            FileInfo* fi = new FileInfo();
            fi->submissiontime = atoi(value1.c_str());
            fi->length= atof(value3.c_str()); 
            fi->finishtime= atoi(value5.c_str());
            fi->remainingtime= atoi(value7.c_str());

            futurelist.push_back(fi); 
        }
    }

    file.close();
}

As for troubling us, don't worry too much about it, you're new here, and still learning. No one knows what they are doing the first time they post.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, please use CODE tags around your code samples in the future; the forum software does not retain the code indentation, and without the formatting the code is almost unreadable.

Second, the data you posted isn't in Comma-Separated-Values (CSV) format, but in a space-separated format. This doesn't seem to be a problem with the code, but it is a bit confusing to those of us reading this and expecting commas. Your code is written to work with a CSV file, so presumably, the actual file is in fact a CSV file.

Third, why did you have a series of separately declared strings (value1, value2, etc.) rather than an array, a structure, or a collection object? Again, it isn't a problem with the program per se, but it seems like a poor design, especially when you later use a list object and thus presumably know how to use collections.

Fourth, you are using a global variable for said list, which is generally considered a poor approach. While this appears to be something of a throw-away program - frankly, I would have used Perl or something like that for a small thing like this - it's still good practice to avoid globals.

Fifth, the list is set to contain objects of type FileInfo, but that class or structure isn't defined anywhere in the given code.

Sixth, you never delete the allocated FileInfo objects. Again, it shouldn't affect the program too much, but it's sloppy coding.

Finally, as for the problem you …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Nevermind, I see Narue found the problem, which I had missed.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Curiously, when using Code::Blocks 10.5 (MinGW GCC 4.4.1), I get the following result from the same dataset:

John Doe
 T00001264
 Freshman
 Second
 0
Jane Doe
 T00012345
 Senior
 First
 3.62

I'm not sure what the cause of the discrepancy in the results is.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Does it work with two strings of greater than zero length? If it does, you may need to test for the string length for both strings.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Good point, I was overthinking things I suppose. My mistake.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Odd, I was having what is in some ways the opposite problem - when I compile and run the program, it accepts the first set of questions and answers, then prints out the series of inquiries for the remaining questions all at once, then ending.

Enter the limit of questions
4
Enter the question
why

enter the four options
why not
because
who knows
fish

Enter the answer for the respective questions
fish
Enter the question
enter the four options
Enter the answer for the respective questions
Enter the question
enter the four options
Enter the answer for the respective questions
Enter the question
enter the four options
Enter the answer for the respective questions

While I was working on that problem, I noticed one thing: as it is now, you are overwriting each question with the next one. You want to have q be a pointer to qa, and assign it a dynamically allocated array. You also need to change how you write to the file, as the way you're doing it now won't work - you need to 'serialize' the separate members of the object one at a time to get consistent results.

This code seems to work now:

#include <iostream>
#include <cstdio>
#include <fstream>
#include <string>

using namespace std;

class qa
{
    char question[35];
    char option[4][20];
    int ans;    //correct option no (eg 0 1 2 3)

public:
    void getques()
    {
        cin.getline(question, 35);
    }


    void getopts()
    {
        for (int i = 0; i < 4; …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Urk, I had missed the use of gets() in the original, or I would have mentioned it... using gets() , under any circumstances, is a serious problem, as it doesn't check to make sure that the input will fit into the buffer it reads into. Using gets() is just asking for buffer overruns; in C++, you should use cin.getline() instead.

void getopts()
{
    for (int i = 0; i < 4; i++)
    {
        cin.getline(option[i], 20);
    }
}

BTW, your indentation style is, to be blunt, atrocious. Please be more careful about indentation, or else use an auto-formatter (VC++ 6.0 includes one, IIRC).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Did you actually mean to mark this 'solved'? You seem to mark it almost as soon as it was posted.

Also, as has been explained before, void main() is incorrect, despite the fact that the compiler says it is acceptable. Please use int main() in C++ programs, always.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You need to move the final word count out of the while() loop. You also need to check for in.fail() in the loop itself, in case there's a problem with the input that did not appear when it was opened.
EDIT: I think I know where the problem lies: you need to use in.get() rather than the << operator to read in the characters. Here's a modified version of your code that ought to work correctly:

#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cctype>

using namespace std;

int main()
{
    int words = 0, count = 0, letters = 0;
    int ch = 0;
    int Option1;
    string FILE;
    cout <<"Hello, This program will count the number of words in a file of your choice!"<<endl;
    cout <<"If you are ready to begin enter 1 and press enter, press 2 and enter to exit."<<endl;
    cin >> Option1;
    if(Option1==2)
    {
        cout <<"Have a nice day"<<endl;
        cout <<endl;
        system("pause");
        return 0;
    }
    if(Option1==1)
    {
        cout <<"Alrighty lets begin, Please enter the name of the file you wish to open"<<endl;
        cout <<"Also include the file format! for example(.txt, .doc, .rtf ect...)"<<endl;
        cin >> FILE;

        ifstream in;
        in.open(FILE.c_str());

        if(in.fail())
        {
            cout << "input file failed to open." << endl;
            exit(1);
        }
        while(!in.eof() && !in.fail())
        {
            ch = in.get();
            // cout.put(ch);
            letters++;

            if((ch=='.') || isspace(ch))
            {
                words++;
            }
        }

        cout << endl;
        cout << "There are " << letters << " characters and" << endl;
        cout << "There are " << words << " …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

To begin with, please use [code] tags around all code samples in the future, especially ones as large as this. This is very important, as the code tags force the software to retain the indentation; without them, the code is almost impossible to read.

#include <iostream>
#include <fstream>
#include <math.h>
#include <string>
using namespace std;

float ran1(long *);

#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
#define NTAB 32
#define NDIV (1+(IM-1)/NTAB)
#define EPS 1.2e-7
#define RNMX (1.0-EPS)

float ran1(long *idum)
{
    int j;
    long k;
    static long iy=0;
    static long iv[NTAB];
    float temp;

    if (*idum <= 0 || !iy)
    {
        if (-(*idum) < 1) *idum=1;
        else *idum = -(*idum);
        for (j=NTAB+7; j>=0; j--)
        {
            k=(*idum)/IQ;
            *idum=IA*(*idum-k*IQ)-IR*k;
            if (*idum < 0) *idum += IM;
            if (j < NTAB) iv[j] = *idum;
        }
        iy=iv[0];
    }
    k=(*idum)/IQ;
    *idum=IA*(*idum-k*IQ)-IR*k;
    if (*idum < 0) *idum += IM;
    j=iy/NDIV;
    iy=iv[j];
    iv[j] = *idum;
    if ((temp=AM*iy) > RNMX) return RNMX;
    else return temp;
}
#undef IA
#undef IM
#undef AM
#undef IQ
#undef IR
#undef NTAB
#undef NDIV
#undef EPS
#undef RNMX

//-------------------------------------------------------------------------------------

//--------------------------------------Defining Energy Function--------------------
double annint(double, double);

double annint (double xcoz, double box) //If xcoz is not between (-0.5 to 0.5 * box) it is taken as part of another box
{
    double co1, co2;
    if (xcoz > 0)
    {
        co1 = (int(xcoz/box))*box;
        return (xcoz-co1);
    }

    else if (xcoz < 0)
    {
        co2 = (int(xcoz/box))*box;
        return (xcoz-co2);
    }
    else
        return(0);
}

// The LJ parameters for …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I am assuming you meant Visual C++, not Visual Basic. Otherwise, you've gotten very confused about the language you are using :?:

The error indicates that the function _tmain() is missing. Now, in UNICODE enabled Windows programs, _tmain() is the equivalent of the main() function in regular C++. That you are getting this now, but not before, seems to me to imply that you'd changed the settings in the project to compile the program for UNICODE, whether you were aware of doing so or not. At least, that's my impression fit it; others may know more about this than I do.

A search on this matter comes up with this advice:

Please change the "subsystem" in your linker settings from "Windows" to "Console".

Whether this will do the trick or not, I am not sure. An alternative solution proposed by R. Stilskin is to

Create a new project following these steps:

When you start the new project wizard, click Win32 Console Application, enter a project name, click OK, then on the next screen click "Application Settings", then "Console application" and "Empty project".

That gives you a completely empty project, so click on Project/Add New Item/C++ File, enter a filename for your main file, and that will open an empty .cpp file.

I am pretty certain that the latter should work even if the former does not.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The link which WaltP provided is to a page for precisely that, actually; this link here gives details on different approaches to indent style, with a specific style (Allman) highlighted. A broad search on indent style or brace style should turn up a plethora of information.

If all else fails, you might also look into editing your code with an IDE that has an auto-indent feature. I have lately been using Code::Blocks a lot lately, and that comes with the Astyle tool which I'd used earlier (under Plugins). Visual C++ Express has a good auto-styler as well.

What editor or IDE are you using? Chances are, it already has support for auto-indentation, even if you don't know it.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You never allocate the memory for the name and branch variables, so when you copy the strings to them, they end up writing to random locations in memory. Add the following to the new and delete operators and it should fix the issue:

void *student::operator new(size_t size)
{
	void *p;
	p = malloc(size);
	(reinterpret_cast<student *>(p))->name = reinterpret_cast<char *>(malloc(16));
	(reinterpret_cast<student *>(p))->branch = reinterpret_cast<char *>(malloc(5));
	return p;
}

void student::operator delete(void *p)
{
  	free(reinterpret_cast<void *>(reinterpret_cast<student *>(p)->name));
  	free(reinterpret_cast<void *>(reinterpret_cast<student *>(p)->branch));
	free(p);
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've gone over the segfault problem, and tracked it down to where you initialize line_counter to 1; you want to initialize it to zero, instead. As it is now, it over-counts the lines by one.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you put the final while() conditional at the beginning of the main() function, and put braces around the rest of the function, it should loop around the whole function:

#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>

using namespace std;

#define DEBUG 0

int Password = -1;
int Option = -1;
char Complete;
string Display;

void pause()
{
 #if (DEBUG != 1)
    system("pause");
#endif
}

void clearScreen()
{
#if (DEBUG != 1)
    system("CLS");
#endif
}

void View_Account()                                                                  //View All Available Accounts
{
    clearScreen();

    cout << "--Viewing All Available Resources--\n" << endl;

    {
        ifstream File ("Log.txt", ifstream::in);

        if(File.good())
        {
            while (!File.eof())
            {
                getline (File, Display);
                cout << Display << endl;
            }
            File.close();
        }
    }
    cout << "\n\nComplete (Y/N): ";
    pause();
}

void Modify_Account()                                                                //Modify All Available Accounts
{
    cout << "Modify Account";

    pause();
}

int main()
{
    while (Option != 6)
    {

        while (Password != 1234)
        {
            clearScreen();

            cout << "Welcome to the MAC Database Search Facility\n" << endl;            //Log In Screen
            cout << "Please enter your password now: ";

            cin >> Password;                                                            //User Input
        }
        clearScreen();

        cout << "Welcome ****, please select your option\n" << endl;                    //Welcome Screen

        cout << "1 - View All Accounts" << endl;                                        //All Available Options
        cout << "2 - Modify an Account" << endl;
        cout << "3 - Delete an Account" << endl;
        cout << "4 - Add an Account" << endl;
        cout << "5 - Search Accounts" << endl;
        cout << "6 - Exit\n" << endl;

        cin >> Option;

        switch (Option)                                                                 //Switch …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oops, I missed that. You need to check whether line_counter is zero in your loop conditional, otherwise it will try to read an non-existent line, causing the segfault.

while(choice != 'q' && line_counter > 0)
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would recommend two changes. First, move the input loop to before the output loop, such that you collect all of the lines before you start outputting the randomly selected lines. Second, after displaying a line, remove that given line from the vector using the single argument version of the erase() method.

int easy()
{
    vector<string> text_file;
    string quest;
    char choice;
    int line_counter = 1;
    srand(time(NULL));

    ifstream myfile ("./questions/easy.txt");
    cout << "Welcome to EASY level category!\n" << endl;

    if (myfile.is_open())
    {
        while( getline( myfile, quest ) )
        {
            text_file.push_back( quest );
            line_counter++;
        }

        while(choice != 'q')
        {
            int line = rand() % line_counter;
            cout << text_file[line];

            text_file.erase(text_file.begin() + line);
            line_counter--;

            cout << "\n\nPress [n] to proceed and [q] to quit: ";
            cin >> choice;
        }

        myfile.close();
    }

    else cout << "Unable to open file";
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I have noticed that there are some problems with the indented code posted by Captain Jake, specifically that some braces appear to be missing. I've used AStyle to automatically re-indent the code, which I hope will help make the main bug clearer:

{ 
    int quantityamount1[3];

    for(int i=0; i<3; i++)
    {
        cout<<"Enter quantity for item "<<i+1<<":\n";
        int quantity=0;
        cin>>quantity;
        if(quantity<=wh[0].amt[i] && wh[0].amt[i]>0)  //Searching current warehouse inventory

            wh[0].amt[i]-=quantity;
        quantityamount1[i]=quantity;
    }
    else
    {
        for(int j=1; j<5; j++)
        {
            if(wh[j].amt[i]>0 && quantity<=wh[j].amt[i])  //Searching other warehouses to fulfill order
            {
                cout<<quantity<<" quantity of item "<<i<<" shipped from "<<wh[j].city<<" to "<<wh[i].city<<"\n";
                wh[j].amt[i]-=quantity;
                cout<<wh[j].city<<"  "<<wh[j].amt[0]<<"  "<<wh[j].amt[1]<<"  "<<wh[j].amt[2]<<"\n";
                break;
            }
            else
            {
                cout<<"Order Unfilled\n";//Could not find any warehouses to fulfill order
                quantityamount1[i]=1;
                break;
            }
        }
        quantityamount1[i]=quantity;
    }
}

The problem lies in the else statement inside the inner for() loop; the way it is currently situated, it will end the loop prematurely. You want to take the clause out of the loop and use a separate if() statement to check whether the loop was exhausted without finding the item in any of the warehouses:

for(int j=1; j<5; j++)
        {
            if(wh[j].amt[i]>0 && quantity<=wh[j].amt[i])  //Searching other warehouses to fulfill order
            {
                cout<<quantity<<" quantity of item "<<i<<" shipped from "<<wh[j].city<<" to "<<wh[i].city<<"\n";
                wh[j].amt[i]-=quantity;
                cout<<wh[j].city<<"  "<<wh[j].amt[0]<<"  "<<wh[j].amt[1]<<"  "<<wh[j].amt[2]<<"\n";
                break;
            }
        }

        if (j >= 5)  // for loop was exhausted without finding the sought items
        {
            cout<<"Order Unfilled\n";//Could not find any warehouses to fulfill order
            quantityamount1[i]=1;
            break;
        }

As an aside: you might want to use named integer constants for …

PrimePackster commented: Thanks for pointing out +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Line 31 should be b = int(a);

I think you meant a = (int) b; , or maybe a = static_cast<int>(b); . Just saying.

EDIT: Just noticed that the variables were reversed, too. I've fixed that now.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'm guessing that the easiest solution involves recursion, and specifically that it is closely related to the integer-to-string algorithm: you accumulate the changes on the stack and rejoin them as the function calls return.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Just curious, I had tried your code and I got "usage: rainfall <current_datafile> <previous_datafile> <output_file>

Process returned 255 (0xFF) execution time : 0.003 s
Press ENTER to continue."

What exactly is going on there?

The version of the program I wrote requires command-line arguments. If you are using Code::Blocks (which I gather is the case), you can go to the Project menu and select Set Programs' Arguments to add the filenames: rainfall_current.dat rainfall_previous.dat rainfall_totals.dat When this is run, it should create a file named rainfall_totals.dat which will contain the generated tables.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Probably the easiest way to convert an integer to a string is by using a stringstream:

int five = 5;

string mystring;
stringstream ss;

ss << five;

ss >> mystring;

A slightly different take on this can be found here; which is better for you depends on what you find convenient.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

How are the boxes defined in the program? Or is that part of what you need help with?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Another side issue I notice while going through the code: you have the following line of code

unsigned int srand = time(0);

However, srand() is a function, which this variable is masking; the result is that the randomizer never actually gets initialized. Also, you only need call srand() once, at the beginning of the program.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As a side issue, why didn't you define the border functions using a for() loop? It would be a lot easier to read and change, if you needed to:

const int LINE_LENGTH = 75;

// ...

void borderDown() 
{
    const char o = 209;

    for (int i = 0; i < LINE_LENGTH; i++)
        cout << o;
    cout << endl << "		";
}

void borderUp()
{
    const char o = 207;

    for (int i = 0; i < LINE_LENGTH; i++)
        cout << o;
    cout << endl;
}

I tested this and it appeared to work the same as the original, so why not do it this way to begin with?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The linker isn't losing track of things; the problem lies in the header, and more specifically, the function prototypes for those two functions. The prototypes are declared as:

void clearBoard(int, char);
void printBoard (char, int);

Whereas the functions themselves are actually:

void clearBoard(int, char*[]);
void printBoard (char*[], int);

This is one place where (IMAO) using fully-qualified function prototypes would help, as it would be clearer where the difference lies:

void clearBoard(int size, char *board[]);
void printBoard(char *board[], int size);
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, passing the filenames by command line might be the best solution of all:

/*
File: Rainfall.cpp
Description: Write a program that reads in the average monthly rainfall for a city for each month
of the year and then reads in the actual monthly rainfall for each of the previous 12 months. The program
then prints out a nicely formnatted table showing the rainfall for each of the previous 12 months as well
as how much below or above average the rainfall was for each month. The average monthly rainfall is given
for months January-December in order. To obtain the actual rainfall for the previous 12 months, the program first
asks what the current month is and then asks for the rainfall figures for the previous 12 months.

After you have completed this program, produce an enhanced version that also outputs a graph showing the
acerage rainfall and the actual rainfall for each of the previous 12 months. Your program should also ask the
user whether they want to see the table or the graph. Include a loop that allows the user tos eee either format as
many times as they wish until they end the program.
*/

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
#include<cmath>

using namespace std;

// Gives the array strings for each of the 12 months. Sets a constant array.
const string Month[12]= {"January", "February", "March",
                         "April", "May", "June",
                         "July", "August", "September",
                         "October", "November", "December"
                        };


// Precondition: Declares the arrays for the current and previous data. …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've gone back to my version of the original algorithm:

double SimpsonArea (int n, int* yValue, double length)
{
    double sum = 0, deltaX;

    for(int i = 0; i < n; i++)
    {
        if ((i == 0) || (i == (n - 1)))
            sum += yValue[i] * 4.0;
        else
            sum += yValue[i];
    }

    deltaX = length / (n - 1);
    return deltaX * sum;
}

... and I'm having trouble seeing where the problem lies. Can you give us the original description of the algorithm that the professor gave you to use?

(Oh, and I simplified the testing process by re-writing the main() function to read the data from a CSV file; I can pass that along as well if you'd like.)

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The first thing I recommend is that, in order to simplify reasoning about the Simpson's Rule function, you should move the part that gathers the elevation data from the function proper, storing the data in an array which you can then pass to the function. You'll need to allocate the array before using it, and delete it after you've finished with it, but this isn't too serious a problem.

Second, I would look at the example implementation on the Wikipedia page about Simpson's Rule, as it may clarify just how the rule normally works.

I have tried to apply both of these suggestions myself, but the function is still not quite correct. Nonetheless, I think that this altered code may help you in working out the correct method.

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

// Prototypes
double SimpsonArea(int, int*, double);

int main()
{
    int NumPoints, RdWidth;
    double RdLength, HillCrossSectionalArea, DirtVolume;
    char Usrp;

    do
    {
        cout << "\n\n";

        cout <<"\nEnter the length of roadway through the hill:";
        cin >> RdLength;
        cout <<"\n      Enter the width of the roadway:";
        cin >> RdWidth;
        cout <<"\nEnter the number of points at which hill";
        cout <<"\n          elevation was measured:";
        cin >> NumPoints;
        cout <<"\nEnter the hill elevations(y values) at the";
        cout <<endl << NumPoints << " equally-spaced points:";
        cout <<"\n\n";

        int *yValues = new int[NumPoints];

        for(int i = 0; i < NumPoints; i++)
        {
            cout <<"Enter y value #" <<i+1 <<":";
            cin >> yValues[i];
        }

        HillCrossSectionalArea = …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

For those sections where you want spaces instead of zeros, simply use setfill(' ') .

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You can use the combination of setw() and setfill('0') .

cout << setw(2) << setfill('0') << day;
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'm not sure about e , but for d , you will want to use the modulo operator, % .

For e , as I said I'm not sure, but I think it has to do with integer division by 5.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In the definition of the Weapon structure, the first letter of the Name member is capitalized. In the code referring to it, the first letter is lowercase ( name instead of Name ). It's the sort of mistake anyone could make, and would have been easy to find except that the compiler error message wasn't very clear.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As is explained here, the maximum value for rand() (defined as RAND_MAX ) is implementation defined, but is at least 32767 for a compliant compiler and library.

As for how to get the specific range you want, you need to use a combination of modulo ( % ) and addition or subtraction. So, for a range of (say) 32,000 to 33,000, you would want a range size of 1000 and an offset of 32,000:

random = (rand() % 1000) + 32000;

Different ranges and offset can be easily selected from this basic pattern.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As I suspected, the declaration for Weapon is missing the semi-colon at the end (line 30).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, that helps quite a bit. The problem is very likely to be in the header files, rather than the using directive itself. It is probably from omitting the semicolon after the declaration of the classes. Can you post Weapon.h and Room.h for us?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you tell us more about the error in question?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I strongly recommend that you first simplify the program thusly:

/*
File: Rainfall.cpp
Description: Write a program that reads in the average monthly rainfall for a city for each month
of the year and then reads in the actual monthly rainfall for each of the previous 12 months. The program
then prints out a nicely formnatted table showing the rainfall for each of the previous 12 months as well
as how much below or above average the rainfall was for each month. The average monthly rainfall is given
for months January-December in order. To obtain the actual rainfall for the previous 12 months, the program first
asks what the current month is and then asks for the rainfall figures for the previous 12 months.

After you have completed this program, produce an enhanced version that also outputs a graph showing the
acerage rainfall and the actual rainfall for each of the previous 12 months. Your program should also ask the
user whether they want to see the table or the graph. Include a loop that allows the user tos eee either format as
many times as they wish until they end the program.
*/

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
#include<cmath>

using namespace std;

// Gives the array strings for each of the 12 months. Sets a constant array.
const string month[12]= {"January", "February", "March",
                         "April", "May", "June",
                        "July", "August", "September",
                        "October", "November", "December"};


// Precondition: Declares the arrays for the current and previous data.
void read_data ( double current_data …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I agree with Rohan121212; you need to give more specifics about the program.

The answer to the question would depend on just how the end of the loop is indicated. If you are given a number of cases to enter before the loop begins, then it is fairly straightforward:

int quiz_count; 

    cout << "Number of quizzes to enter: ";
    cin >> quiz_count;
    cin.ignore();
    for (int i = 0; i < quiz_count; i++)
    {
        read_quiz();
    }

OTOH, if you don't have the number of quizzes ahead of time, a while() or do..while() loop would be better:

do 
    {
        read_quiz();

        char another_quiz;
        cout << "Enter another quiz (Y/N)? ";
        cin >> another_quiz;
        cin.ignore();
    } while (toupper(another_quiz) == 'Y');

Do either of these solve your problem?

TaoNinja commented: Helped me out ^_^ +1