m4ster_r0shi 142 Posting Whiz in Training

Well, the compiler said the problem was with load_image, not load_files. The definition of load_files you post here is irrelevant to the problem.

Now, about the other problems (multiple definition of some functions). Maybe you're declaring and defining these functions in a header file and then include that header file in both main.cpp and playa.cpp. If that's the case, either declare these functions inline or put the definitions in a separate cpp file and see what happens.

m4ster_r0shi 142 Posting Whiz in Training

not all control paths return a value

This means that you have code that looks like this:

ReturnType load_image(ArgType1 arg1, ArgType2 arg2, ...)
{
    //...

    if (some_condition) return something;

    // What happens if some_condition is false?
    // You don't return anything in that case...
}

The first two aren't errors that mess with the program.

While they don't affect compilation, they might seriously mess your program after you manage to compile it :)

m4ster_r0shi 142 Posting Whiz in Training

Careful! The relevant threads in the Software Development and Web Development forum categories are not sticky!

Or at least that's what I see...

not_sticky

m4ster_r0shi 142 Posting Whiz in Training

@OP: Moschops is right. I fixed these errors, compiled the code you posted and got the expected output.

m4ster_r0shi 142 Posting Whiz in Training

Boost is unnecessary

Sure. Cars are unnecessary too, since we can walk. Joking aside, this is not a well formed statement. Boost consists of many different libraries and covers a wide range of uses. Some of these components are highly portable and extremely useful for any project (e.g. smart pointers). Why not use them?

It's better at the early stages of learning to do things by scratch

Sometimes it is. Sometimes it isn't. If you decide to start learning game programming, your first project should not be building a rendering engine from scratch. You'll first use an existing engine to draw and move shapes and sprites on the screen. Similarly, if you're interested in parsing, it's better to use an existing framework at first. If you do it from scratch, it'll probably take you a while before seeing a tangible result of your effort and this might act as an inhibitive factor to your learning experience.

It's also non-standard...

Again, you're putting everything in the same bag. Also, don't forget that part of boost is (was?) non-standard simply because the C++ standard is left behind. There are many languages that support lambas, regexes, threading... etc... out-of-the-box. C++ was not one of them until recently. And many of these things were taken from boost.

When you change languages/systems, Boost may not be an option and if that's what you learned you are SOL and can't write the code.

I really don't know what …

m4ster_r0shi 142 Posting Whiz in Training

I see that the OP is still following this thread, so, in case (s)he decides to take the boost approach, here's something (s)he might find useful, as the spirit documentation on building syntax trees is inadequate (IMO). Also, since that article uses an earlier version of spirit, here's an example using the current version.

Usage example:

type an expression... or empty line to quit

-(1+2)*(1+3)^2
-48
print "hello, world!"
hello, world!
print 1+2^3*5
41
print "1+2+3"
1+2+3
print "hi
invalid expression...
1+2*/3
invalid expression...
m4ster_r0shi 142 Posting Whiz in Training

If you are writing a simple program that resembles a language interpreter, and it is capable of computing non-trivial equations of more than a fixed size, then you really are talking about writing an intepreter. You'll want to go the whole route of tokenizing and parsing the input, even if the input is supposed to be limited in scope.

I agree with the above. Don't do everything from scratch though. Do yourself a favour and take a look at Boost.Spirit. Here's a minimal example:

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

#include <iostream>
#include <sstream>
#include <string>

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

template <typename Iterator>
struct interpreter_grammar : qi::grammar<Iterator, int(), ascii::space_type>
{
    interpreter_grammar() : interpreter_grammar::base_type(entry)
    {
        using namespace qi::labels;

        entry = math_expression [_val = 1] | print_math_expression [_val = 2] | print_expression [_val = 3];
        math_expression = term >> *( ('+' >> term) | ('-' >> term) );
        term = qi::double_ >> *( ('*' >> qi::double_) | ('/' >> qi::double_) );
        print_math_expression = qi::lexeme["print" >> qi::space] >> math_expression;
        print_expression = qi::lexeme["print" >> qi::space] >> +qi::char_;
    }

    qi::rule<Iterator, int(), ascii::space_type> entry;
    qi::rule<Iterator, ascii::space_type> print_expression,
        print_math_expression, math_expression, term;
};

double evalMathExpr(std::string expr)
{
    double operand1, operand2, result, number;
    char operation;

    std::stringstream buffer(expr + '#'), ssResult;

    buffer >> operand1;

    while (buffer >> operation)
    {
        switch(operation)
        {
            case '+': case '-': ssResult << operand1 << operation; buffer >> operand1; break;
            case '*': buffer >> operand2; operand1 *= operand2; break;
            case '/': buffer >> operand2; operand1 /= operand2; break;
            case …
m4ster_r0shi 142 Posting Whiz in Training

Oh, well, I was hoping I could avoid this...

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

using namespace std;

BOOL CALLBACK printClassName(HWND hwnd, LPARAM lParam)
{
    CHAR buffer[512];

    GetClassNameA(hwnd, buffer, 511);

    cout << buffer << endl;

    return TRUE;
}

int main()
{
    ifstream fin("C:/in.txt");

    string line2;

    getline(fin, line2);
    getline(fin, line2);

    string className;

    cout << "window class names: " << endl;
    EnumWindows(printClassName, NULL);

    cout << "enter window class name: ";
    getline(cin, className);

    HWND hwnd = FindWindow(className.c_str(), NULL);
    if (hwnd == NULL)
    {
        cout << "couldn't find window...";
        cin.get(); return 0;
    }
    cout << "got it!" << endl;

    cout << "control class names: " << endl;
    EnumChildWindows(hwnd, printClassName, NULL);

    cout << "enter control class name: " << endl;
    getline(cin, className);

    HWND control = FindWindowEx(hwnd, NULL, className.c_str(), NULL);
    if (control == NULL)
    {
        cout << "couldn't find control...";
        cin.get(); return 0;
    }
    cout << "got it!" << endl;

    SendMessage(control, WM_SETTEXT, 0, (LPARAM)line2.c_str());

    cin.get();
}

After opening notepad, I ran the above, entered "Notepad", then "Edit", and it worked as expected.

m4ster_r0shi 142 Posting Whiz in Training

I think you may be using the wrong language for this. It's certainly doable, but there
are much better alternatives (at least on windows). One such alternative is Autoit.

Here's an example that does what you want with notepad:

$file = FileOpen("C:/in.txt")
$line2 = FileReadLine($file, 2)
Run("notepad.exe")
WinWait("[CLASS:Notepad]")
ControlSend("[CLASS:Notepad]", "", "Edit1", $line2)
m4ster_r0shi 142 Posting Whiz in Training

If you have to do it using sscanf, you could do it like this:

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    string path = "main/articles/animals/giraffe";

    char * cPath1 = new char[path.size()];
    char * cPath2 = new char[path.size()];

    sscanf(path.c_str(), "%[^'/']/%[]", cPath1, cPath2);

    string path1(cPath1), path2(cPath2);

    delete[] cPath1; delete[] cPath2;

    cout << path1 << '\n' << path2 << endl;

    cin.get();
}

But why not do it the C++ way?

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string path = "main/articles/animals/giraffe";

    stringstream stream(path);
    string part1, part2;

    getline(stream, part1, '/');
    getline(stream, part2);

    cout << part1 << '\n' << part2 << endl;

    cin.get();
}

A couple of useful links -> sscanf, stringstream, getline

OrangeTree commented: Clearly and useful. +0
m4ster_r0shi 142 Posting Whiz in Training

You don't really need to understand how std::map works in order to understand how to use it.
I have an idea. Let's ask the OP which version (s)he finds easier to implement / understand.
This one -> http://ideone.com/ojv1H ? Or this one -> http://ideone.com/Vz9oh ?

m4ster_r0shi 142 Posting Whiz in Training

Your assumtion was how the input is being made as shown by linking to that article.

It's not an assumption. The OP mentioned scanf and (s)he also provided an example of how the input is made in his/her program.

Where have I suggested not programming properly?

The OP provided the way (s)he gets input and you suggested a large static array as a solution. This implies one or more of the following:

(1) You didn't know the way the OP gets input (perhaps because you didn't bother to read the other posts).
(2) You didn't know that this combination of input - storing strategy could lead to a problem.
(3) You knew that this combination of input - storing strategy could lead to a problem, but you didn't want to tell the OP (either because you didn't think it's important or because you didn't want the OP to know).

In the end, either you didn't notice there was a problem or you suggested a bad programming practice on purpose. Which one is it?

the dynamic memory situation would be identical even in the link you posted

Not quite. Corrupting the heap in an exploitable way is different than corrupting the stack in an exploitable way (e.g. AFAIK, you can't directly modify the instruction pointer by corrupting the heap. All you can do is mess up malloc's internal structures).

m4ster_r0shi 142 Posting Whiz in Training

How does this create a huge security hole and reallocating the array by 1 for each input doesn't?

The answer to the first part of your question is provided in the link I posted above. The answer to the second part of your question was provided by Sokurenko.

Keep in mind the info we have been given by the OP, not making unfounded assumptions about what we haven't been told...

I'm not sure I understand what you mean here. Either this is homework or it's not. I cover both cases in my post: If it's homework, a large static array is fine. If it's not homework, a large static array is a problem. You're the one who's making assumptions, by ignoring the fact that this may not be homework. Unless you mean something else.

m4ster_r0shi 142 Posting Whiz in Training

Why not just create array as a large array? Say int array[1000]?

While this would work if this is just homework, it's not a good idea in general, as it creates a huge security hole in the application. Here's an interesting thread I found regarding that matter.

The concept of increasing the array size by one for each and every value entered is so resource heavy that I don't really think a useful solution.

It's not that bad, actually. If the user enters 10000 integers before (s)he stops, the total resizing and copying process would take less than 100 milliseconds. But, of course, it's not the wisest thing to do.

In my opinion, the best thing you can do is emulate the inner workings of a std::vector. That is, create an dynamic array of, let's say, 100 elements, at first. If the user enters more than 100 integers, resize that array to 200 elements (using the functions mentioned above -- no, you can't escape that). If the user enters more than 200 elements, resize your array to hold 400 elements, etc... Once the user decides to stop, you can optionally resize your array one last time, if saving memory is really that important.

m4ster_r0shi 142 Posting Whiz in Training

That way u dont have to change ur function template everytime if u wish to change the m x n of ur array...

This doesn't make sense. You never have to change your function template.

Its faster

No, it's not.

#include <iostream>
#include <boost/timer.hpp>

using namespace std;

double global;

template <int M, int N>
void speedTest(int (& array)[M][N])
{
    for (int i = 0; i < M; ++i)
        for (int j = 0; j < N; ++j)
            array[i][j] = 0;

    global++;
}

void speedTestPtr(int * array, int M, int N)
{
    for (int i = 0; i < M; ++i)
        for (int j = 0; j < N; ++j)
            array[i*N + j] = 0;

    global++;
}

int main()
{
    int arr2x2[2][2] = {{1, 2}, {3, 4}};

    boost::timer timer;

    timer.restart();

    for (long i = 0; i < 10000000; ++i)
    for (long j = 0; j < 15; ++j)
        speedTest(arr2x2);

    cout << "time 1: " << timer.elapsed() << endl;

    timer.restart();

    for (long i = 0; i < 10000000; ++i)
    for (long j = 0; j < 15; ++j)
        speedTestPtr(&arr2x2[0][0], 2, 2);

    cout << "time 2: " << timer.elapsed() << endl;

    cout << global << endl;

    cin.get();
}

I tested the above with zero, -O1, -O2 and -O3 speed optimizations. The results I got were, respectively:

time 1: 3.5
time 2: 4.1

time 1: 0.7
time 2: 1.7

time 1: 0.234
time 2: 0.281

time 1: 0.187
time 2: 0.187

can be …

m4ster_r0shi 142 Posting Whiz in Training

Don't forget to get the debug privilege before opening a process other than your own. Useful link.
Also, don't forget to close your handles once you're done (I forgot to do it...). Another useful link.

m4ster_r0shi 142 Posting Whiz in Training

It's impossible to pass a C array by value (see why here).
If you want a function that can handle 2x2 and 3x3 and,
in general, MxN arrays, you could use a function template.

#include <iostream>

using namespace std;

void print2x2(int array[2][2])
{
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
            cout << array[i][j] << ' ';
        cout << '\n';
    }

    cout << endl;
}

void dec2x2(int array[2][2])
{
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            array[i][j]--;
}

template <class T, int M, int N>
void print(T (& array)[M][N])
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
            cout << array[i][j] << ' ';
        cout << '\n';
    }

    cout << endl;
}

template <class T, int M, int N>
void dec(T (& array)[M][N])
{
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
            array[i][j]--;
}

int main()
{
    int arr2x2[2][2] = {{1, 2}, {3, 4}};
    double arr3x3[3][3] = {{1.1, 2.2, 3.3}, {4.4, 5.5, 6.6}, {7.7, 8.8, 9.9}};

    print2x2(arr2x2);
    dec2x2(arr2x2);
    print2x2(arr2x2);

    print(arr3x3);
    dec(arr3x3);
    print(arr3x3);

    cout << "hit enter to quit...";
    cin.get();
}
m4ster_r0shi 142 Posting Whiz in Training

What do you mean by saying "fix"? Regarding that particular example, if you look at the relevant code, you'll see that it uses a basic JPanel and adds a vertical glue and the button panel to it (in that order). If you want the buttons to be up, you should add the glue after adding the button panel (you'll also have to move the rigid area above the buttons if you don't want them to stick to the title bar):

public final void initUI() {

    //...

    //basic.add(Box.createVerticalGlue()); // <- remove this

    //...

    basic.add(Box.createRigidArea(new Dimension(0, 15))); // <- add this
    basic.add(bottom);
    //basic.add(Box.createRigidArea(new Dimension(0, 15))); // <- remove this

    basic.add(Box.createVerticalGlue()); // <- add this

    //...
}

You can find more about glues and rigid areas in the first link cOrRuPtG3n3t!x mentioned.

m4ster_r0shi 142 Posting Whiz in Training

Here's another good link. My personal favourite is the Box Layout:

import java.awt.Dimension;
import java.awt.Font;

import javax.swing.*;

public class Main extends JFrame {

    void init() {

        // we'll use a main panel and four row-panels

        JPanel basicPanel = new JPanel(); basicPanel.setLayout(
            new BoxLayout(basicPanel, BoxLayout.Y_AXIS));

        JPanel titleRow = new JPanel(); titleRow.setLayout(
            new BoxLayout(titleRow, BoxLayout.Y_AXIS));

        JPanel usernameRow = new JPanel(); usernameRow.setLayout(
            new BoxLayout(usernameRow, BoxLayout.X_AXIS));

        JPanel passwordRow = new JPanel(); passwordRow.setLayout(
            new BoxLayout(passwordRow, BoxLayout.X_AXIS));

        JPanel buttonRow = new JPanel(); buttonRow.setLayout(
            new BoxLayout(buttonRow, BoxLayout.X_AXIS));

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= title panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        JLabel lblAdmin = new JLabel("ADMIN"); lblAdmin.setAlignmentX(0.5f);
        lblAdmin.setFont(lblAdmin.getFont().deriveFont(Font.BOLD).deriveFont(50f));

        JLabel lblConsole = new JLabel("CONSOLE"); lblConsole.setAlignmentX(0.5f);
        lblConsole.setFont(lblConsole.getFont().deriveFont(Font.ITALIC).deriveFont(40f));

        titleRow.add(lblAdmin);
        titleRow.add(lblConsole);

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= username panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        JLabel lblUsername = new JLabel("username:");
        JTextField txtUsername = new JTextField();
        txtUsername.setMaximumSize(new Dimension(125, 25));

        usernameRow.add(lblUsername);
        usernameRow.add(Box.createRigidArea(new Dimension(10, 0)));
        usernameRow.add(txtUsername);

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= password panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        JLabel lblPassword = new JLabel("password:");
        JTextField txtPassword = new JTextField();
        txtPassword.setMaximumSize(new Dimension(125, 25));

        passwordRow.add(lblPassword);
        passwordRow.add(Box.createRigidArea(new Dimension(10, 0)));
        passwordRow.add(txtPassword);

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= button panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        JButton btnLogIn = new JButton("Log In");
        JButton btnCancel = new JButton("Cancel");

        btnLogIn.setMinimumSize(new Dimension(80, 30));
        btnLogIn.setMaximumSize(new Dimension(80, 30));

        btnCancel.setMinimumSize(new Dimension(80, 30));
        btnCancel.setMaximumSize(new Dimension(80, 30));

        buttonRow.add(btnLogIn);
        buttonRow.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonRow.add(btnCancel);

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= main panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        basicPanel.add(Box.createVerticalGlue());
        basicPanel.add(titleRow);
        basicPanel.add(Box.createRigidArea(new Dimension(0, 30)));
        basicPanel.add(usernameRow);
        basicPanel.add(Box.createRigidArea(new Dimension(0, 10)));
        basicPanel.add(passwordRow);
        basicPanel.add(Box.createRigidArea(new Dimension(0, 20)));
        basicPanel.add(buttonRow);
        basicPanel.add(Box.createVerticalGlue());

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= frame stuff =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        add(basicPanel);

        setSize(240, 320);
        setTitle("Box Layout Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {

                Main app = new Main();

                app.init();
                app.setVisible(true);
            }           
        });
    }
}
m4ster_r0shi 142 Posting Whiz in Training

I am sure this guy can pass also his next course if he gets 50 % of your post oh Mysterious master!

:) :) :) I'm sure he'll eventually be able to get 100 % of it.

For me the loop is against the general idea of the stack so I would add one variable for total of stack for each stack.

Ah, right. After all, a stack is supposed to only allow access on the topmost element (I forgot that restriction in the code above too...).

EDIT:

the last bit in docstring use example with Master's input gives different stacks than he gives

Yes, that's because, in python terms, my code looks like...

if sum(stack1) <= sum(stack2):

instead of...

if not stack1 or sum(stack1) + item <= sum(stack2):

m4ster_r0shi 142 Posting Whiz in Training

Oh, come on, guys, don't be so harsh. Let's help him get started...

You could use two big sized arrays to represent your stacks. You'll have to also use two integers (initialized to zero) to keep track of each stack's current size. When you want to add a number to a stack, put it to stack[cur_size] and then increment cur_size by one. Don't forget to make sure that your arrays (stacks) are of the appropriate data type (look at the numbers the user is allowed to enter). You can easily get the sum of each stack at any time using a loop. The main part of your program would also be one big loop whose body is repeated n times.

Show us what you can make out of that, and we'll gladly help you more.

Now, this looked like a good metaprogramming exercise and I was bored, so I gave it a shot...

main.cpp

#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/seq.hpp>

#include <boost/mpl/push_back.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/deque.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/if.hpp>

#include <iostream>

#define MAKE_MPL_INTS(r, data, elem) ,int_< elem >
#define MAKE_MPL_INT(elem) int_< elem >

#define APPLY_OP_STEPS(r, data, elem) ::apply::result
#define APPLY_OP_STEP apply::result

#define input_seq (0)(8)(7)(2)(4)(1)(3)(5)(6)(9)

using namespace boost::mpl;

template <class container> struct sum { typedef typename fold<container, int_<0>, plus<_1, _2> >::type type; };

template <class input_, class stack1_, class stack2_>
struct state { typedef input_ input; typedef stack1_ stack1; typedef stack2_ stack2; };

template <class state_>
struct op_step
{
    typedef state_ cur_state;

    struct apply
    {
        typedef …
m4ster_r0shi 142 Posting Whiz in Training

Ah, right, I forgot about that one. And here you can see why you should prefer Random.nextInt(n) to (int) (Math.random() * n).

m4ster_r0shi 142 Posting Whiz in Training

What if you cast rnd2 to an int?

ques.setText(questions[(int) rnd2]);

Note that you don't really need Math.ceil here. You could just do...

ques.setText(questions[(int) (Math.random() * questions.length)]);

m4ster_r0shi 142 Posting Whiz in Training

Obviously, this...

for(int i = 0; i > nrEle ; i++){
    for(int j = 0; j > nrEle; j++){

should be...

for(int i = 0; i < nrEle ; i++){
    for(int j = 0; j < nrEle; j++){
m4ster_r0shi 142 Posting Whiz in Training

If you have to code this yourself, one way to do it would be to use the inverse transformation and acceptance-rejection methods.

I had to simulate normal distribution a while ago and that's how I did it:

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>

using namespace std;

double random() { return rand() / double(RAND_MAX); }

struct Distribution
{
    virtual double Draw() { return 0.0; }
    virtual ~Distribution() {}
};

struct UniformDistribution : Distribution
{
    double a, b;

    UniformDistribution(double a_ = 0.0, double b_ = 1.0) :  a(a_), b(b_) {}
    ~UniformDistribution() {}

    // inverse transform sampling
    double Draw() { return a + (b - a) * random(); }
};

struct NormalDistribution : Distribution
{
    UniformDistribution ud1, ud2;

    double mean, dev, max;

    NormalDistribution(double mean_, double dev_) : mean(mean_), dev(dev_)
    {
        max = 1.0 / sqrt(2 * 3.14159265 * dev * dev);

        ud1 = UniformDistribution(mean - 4 * dev, mean + 4 * dev);
        ud2 = UniformDistribution(0, max);
    }
    ~NormalDistribution() {}

    double density(double x) { return max * exp(- (x - mean) * (x - mean) / (2 * dev * dev)); }

    // rejection sampling
    double Draw()
    {
        double x = ud1.Draw();
        double y = ud2.Draw();

        if (y <= density(x)) return x;
        else return Draw();
    }
};

int main()
{
    srand(time(0));

    NormalDistribution nd(10, 2);

    vector<double> random_numbers;

    for (size_t i = 0; i < 100; ++i) random_numbers.push_back(nd.Draw());

    sort(random_numbers.begin(), random_numbers.end());

    for (size_t i = 0; i < 100; ++i) cout << random_numbers[i] << endl;
} …
m4ster_r0shi 142 Posting Whiz in Training

I have a vector of doubles and I need to [...] write the contents to a text file.

What's wrong with simply opening the file in text mode, iterating through your vector and outputing each double?

main.cpp

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    vector<double> vec;

    vec.push_back(1.2345678935);
    vec.push_back(2.1957203851);
    vec.push_back(3.2230343852);
    vec.push_back(0.5534203832);

    ofstream fout("out.txt");

    fout.setf(ios::fixed);
    fout.precision(10);

    for (size_t i = 0; i < vec.size(); ++i)
        fout << vec[i] << '\n';

    fout.close();
}

out.txt

1.2345678935
2.1957203851
3.2230343852
0.5534203832
m4ster_r0shi 142 Posting Whiz in Training

I'm not sure how I would check if the values are 'parse-able' or not

You could use a stringstream for that. First, get rid of the trailing whitespace characters in your input. Then, create a stringstream out of your input and use it to set your variable's value. If the operation succeeds and there is no data left in your stringstream object, you're OK.

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

template <class T>
bool TryParse(string input, T & var)
{
    static const string ws(" \t\f\v\n\r");

    size_t pos = input.find_last_not_of(ws);

    if (pos != string::npos)
        input.erase(pos + 1);
    else input.clear();

    stringstream buffer(input);

    return buffer >> var && buffer.eof();
}

int main()
{
    string input;

    int n;
    double d;

    while (cin) // CTRL-Z (or CTRL-D) and enter to quit
    {
        cout << "enter int: "; getline(cin, input);
        if (TryParse(input, n))
            cout << "you entered: " << n << endl;
        else cout << "error" << endl;

        cout << "enter double: "; getline(cin, input);
        if (TryParse(input, d))
            cout << "you entered: " << d << endl;
        else cout << "error" << endl;
    }
}
m4ster_r0shi 142 Posting Whiz in Training

You really should google more before posting. Look, I found a thread with a guy having the exact same code and a very similar problem to the one you're having. Considering the degree of similarity, I believe the replies he got should also be applicable to your case.

m4ster_r0shi 142 Posting Whiz in Training

[...] The second should accept two arguments of type string (not C-string types) [...]

Why do you use C-strings in your code then?

[...] Intuitively I would think template in C++ [...]

You're right. Your maximum function template works fine for both doubles and std::strings. Also, as nullptr noticed, you'll have to write an overload if you want your function to behave properly for C-strings.

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

template <class T>
T maximum(T first, T second)
{
    cout << "(using function template) ";

    return first > second ? first : second;
}

const char * maximum(const char * first, const char * second)
{
    cout << "(using const char * overload) ";

    return strcmp(first, second) > 0 ? first : second;
}

int main()
{
    cout << maximum(5, 2) << endl;
    cout << maximum(7L, 3L) << endl;
    cout << maximum(1.2, 3.4) << endl;
    cout << maximum(2.3f, 5.5f) << endl;
    cout << maximum("abc", "abd") << endl;
    cout << maximum(string("abc"), string("abd")) << endl;
}
m4ster_r0shi 142 Posting Whiz in Training

It didn't work because you did something like this:

while (numbersList >> type >> num1 >> num2) // you read a line here
{
    Complex *object = new Complex(type,num1,num2);
    numbersList >> type >> num1 >> num2; // and then you read another line here
    cout << "For line number " << n << ": " << endl;
    object->printAll();
    cout << endl;
    n++;
}

It will work fine if you do it like this:

while (numbersList >> type >> num1 >> num2)
{
    Complex *object = new Complex(type,num1,num2);
    // numbersList >> type >> num1 >> num2;
    cout << "For line number " << n << ": " << endl;
    object->printAll();
    cout << endl;
    n++;
}

Also, you don't really need dynamic memory allocation here, if you only want to print the contents of the file. This would work fine:

while (numbersList >> type >> num1 >> num2)
{
    cout << "For line number " << n << ": " << endl;
    Complex(type,num1,num2).printAll();
    cout << endl;
    n++;
}
m4ster_r0shi 142 Posting Whiz in Training

What if you make your get functions return references?

vector<string> & getcoursename() {return coursename;}
vector<double> & getmark() {return mark;}
NathanOliver commented: I missed that one. Good Job +0
m4ster_r0shi 142 Posting Whiz in Training

If you want to restrict input to integers in [1, 5], your while condition should be different.

One way to do it is by using two relational operators and the logical OR operator.

m4ster_r0shi 142 Posting Whiz in Training

Actually, this is one of the things the OP, surprisingly, did right. I'm saying "surprisingly" because this is a very common mistake among beginners. Assuming...

string word;
ifstream file("in.txt"); // in.txt contains a list of words

...what most beginners do when reading that file is this:

while (!file.fail())
{
  file >> word;

  //do something with word
}

As a result, there are tons of "Help! Last line of the file processed twice!" threads all around the web. After they realize that they must check the stream status right after the input operation, they usually change their code to something like this...

while (true)
{
  file >> word;

  if (file.fail()) break;

  //do something with word
}

...which, of course, works, but is not as elegant as this one:

while (file >> word)
{
  //do something with word
}

True, the OP got carried away and added an unnecessary (but harmless here) "&& schoolEnrollment" part, but if you scratch that one, the rest is ok. It could be a bit more concise though:

while (inputFile >> schoolName >> schoolLocation >> schoolEnrollment >> schoolCost)
{
  // do stuff...
}

Now, about the actual problem. The solution is very simple. You just have to add an assignment statement inside each loop. When you change the max variable, also change the respective school name to the current school name.

Also, don't forget to close the file before opening it for the third time.

m4ster_r0shi 142 Posting Whiz in Training

Sorry. Forget the 65536 vs 4294967296 and 10000 vs 1000000000 stuff. I forgot that 64 bit integers were standardized...

m4ster_r0shi 142 Posting Whiz in Training

I have a couple of things to say regarding the base choice. In general, you'll want your base to be as big as possible, because this implies faster operations. However, there are other factors you should also consider, such as potential overflow during operations and conversion time from and to other bases.

If you want your bignum class to be as fast as possible, you can choose your base to be sqrt(4294967296) = 65536 (not 4294967296, because then there is the possibility of overflow during multiplication/addition). However, if you do it like this, input and output in dec are not trivial matters.

If you want to save yourself the base conversion stuff and still have some decent speed, you can choose your base to be 10000 (not 1000000000, because of the multiplication/addition overflow potential). 10000 and 65536 are of almost the same order, so there's no considerable performance loss. Plus, input and output in dec are piece of cake. I'd go with that.

Walt's approach (base 10) is probably the simplest/easiest way to go, but you wouldn't want to use it for serious bignum crunching, as it's quite slow (but then again, if you want serious bignum crunching, you'd be better off using GMP or something like that).

this is something like a hobby when I do only during free time

I trust that you're telling the truth, so here's something to get you started -> http://ideone.com/2aBA1 Note that there's no support …

m4ster_r0shi 142 Posting Whiz in Training

Hmmm... Interesting stuff from mike... Ok, this one should demonstrate the difference better:

#include <iostream>
#include <cstdlib>

#include <boost/timer.hpp>

// policy version
template < class OperationPolicy>
struct DoOperationPolicy : OperationPolicy
{ void Run(double a, double b) { OperationPolicy::Operation(a,b); } };

struct OperationPolicyAdd { double Operation(double a, double b) { return a + b; } };
struct OperationPolicySub { double Operation(double a, double b) { return a - b; } };
struct OperationPolicyMul { double Operation(double a, double b) { return a * b; } };
struct OperationPolicyDiv { double Operation(double a, double b) { return a / b; } };

// polymorphic version
struct DoOperation { virtual double Run(double a, double b) = 0; };

struct OperationAdd : DoOperation { double Run(double a, double b) { return a + b; } };
struct OperationSub : DoOperation { double Run(double a, double b) { return a - b; } };
struct OperationMul : DoOperation { double Run(double a, double b) { return a * b; } };
struct OperationDiv : DoOperation { double Run(double a, double b) { return a / b; } };

int main()
{
    boost::timer timer;

    const unsigned int numberOfIterations = 1e7;

    DoOperationPolicy<OperationPolicyAdd> policy_operation_add;
    DoOperationPolicy<OperationPolicySub> policy_operation_sub;
    DoOperationPolicy<OperationPolicyMul> policy_operation_mul;
    DoOperationPolicy<OperationPolicyDiv> policy_operation_div;

    timer.restart();

    for(unsigned int i = 0; i < numberOfIterations; ++i)
    {
        switch(rand()%4)
        {
            case 0 : policy_operation_add.Run(rand()%9+1, rand()%9+1); break;
            case 1 : policy_operation_sub.Run(rand()%9+1, rand()%9+1); break;
            case 2 : policy_operation_mul.Run(rand()%9+1, rand()%9+1); break;
            case 3 : policy_operation_div.Run(rand()%9+1, rand()%9+1); break;
            default : ;
        }
    }

    std::cout << timer.elapsed() << " …
m4ster_r0shi 142 Posting Whiz in Training

Without optimizations, I get:

0.078 seconds.
0.047 seconds.

With -O3 (best speed optimization) and after
setting numberOfIterations to 1e9 , I get:

0 seconds.
3.297 seconds.

I use the version of mingw that comes along with the latest Code::Blocks.

m4ster_r0shi 142 Posting Whiz in Training

Yes. Look up template template parameters.

m4ster_r0shi 142 Posting Whiz in Training

Why do you want to specify the template parameters explicitly?
I'm not really sure I understood what you want, so I'll just list a
couple of things hoping one or two of them suits your needs.

#include <iostream>
#include <vector>

template <class T> class Simple { };

template <class T>
class MyClass
{
public:

    template <class U>
    void Output(const U & object)
    { std::cout << "any_type" << std::endl; }

    void Output(const T & object)
    { std::cout << "just T" << std::endl; }

    void Output(const MyClass<T> & object)
    { std::cout << "MyClass < T >" << std::endl; }

    template <class U>
    void Output(const MyClass<U> & object)
    { std::cout << "MyClass < any_type >" << std::endl; }

    template <template <class> class U>
    void Output(const U<T> & object)
    { std::cout << "any_type < T >" << std::endl; }

    template <template <class> class U>
    void Output(const MyClass<U<T> > & object)
    { std::cout << "MyClass< any_type < T > >" << std::endl; }

    template <template <class> class U, class V>
    void Output(const U<V> & object)
    { std::cout << "any_type < any_type >" << std::endl; }

    template <template <class> class U, class V>
    void Output(const MyClass<U<V> > & object)
    { std::cout << "MyClass< any_type < any_type > >" << std::endl; }
};

int main()
{
    MyClass<char> my_class_c;
    MyClass<int>  my_class_i;

    Simple<char> simple_c;
    Simple<int>  simple_i;

    my_class_i.Output(0);
    my_class_i.Output('0');

    std::cout << std::endl;

    my_class_i.Output(simple_i);
    my_class_i.Output(simple_c);

    std::cout << std::endl;

    my_class_i.Output(my_class_i);
    my_class_i.Output(my_class_c);

    std::cout << std::endl;

    MyClass<Simple<int> > my_class_si;

    my_class_i.Output(my_class_si);
    my_class_c.Output(my_class_si);
}

EDIT: Added one more case.

m4ster_r0shi 142 Posting Whiz in Training

Another reason might be that your program can't find SDL.dll and/or SDL_image.dll. The former comes along with SDL but
the latter doesn't (AFAIK). You can get it from here -> SDL_image. Copy these two dlls next to your exe and see if it works.

EDIT:

Hmmm... It looks like you'll also need libpng12-0.dll (you can find it in the same link).
Also, make sure that both dot.bmp and bg.png are in the appropriate directory.

m4ster_r0shi 142 Posting Whiz in Training

Well, as I said above, you can't do it like this. Leave that as it is and write
another function to print the polynomial, using the pseudocode I posted
above. It shouldn't be too difficult, unless the code you posted isn't yours.

m4ster_r0shi 142 Posting Whiz in Training

I don't think I can use cout

But, how will you print anything without using cout?

part of my problem is that I'm not sure how I can let x stay as a character since it is a part of the formula and the function

You can't do it like this. You'll have to use two loops:

for i = 0 -> N
{
    if ( /* something involving i */ ) print "+"

    print "("
    print f[x0, ..., xi]
    print ")"

    for j = ??? -> ???
    {
        print "(x-"
        print xj
        print ")"                
    }
}
m4ster_r0shi 142 Posting Whiz in Training

It shouldn't be too difficult. You could either create another function to display the polynomial or add a couple of cout statements in your current function. In either case, you'll probably need two for loops, an outer one that will iterate over f(x0), f[x0, x1], ..., f[x0, ... xn] and an inner one that will iterate over x0, x1, ..., xk, for each f[x0, ..., xk] (it looks like you store x0, x1, ..., xk as trap[0][0], trap[1][0], ..., trap[k][0], so, you already have everything you need). By the way, I believe you also need to use two loops in order to compute the value of the polynomial (which implies that your current code doesn't calculate the result correctly).

Also, I have a question too: Do you need this for Mrs. Gousidou's exercise?

EDIT:

Ok, I see what you do now. You don't need two loops to compute the result. But if you want to print the polynomial, you'll need two loops.

m4ster_r0shi 142 Posting Whiz in Training

Okay. In this case, an indirect_iterator is exactly what you need.

daviddoria commented: Yep, that is certainly what I was looking for! +12
m4ster_r0shi 142 Posting Whiz in Training

Another option would be to use Boost.Iterator.

m4ster_r0shi 142 Posting Whiz in Training

You don't have to call strlen or any other function to compute your word's length.
Notice that, inside your loop, c represents the number of correct consecutive letters.
Just add a bool variable outside your loop and modify it appropriately inside the loop:

bool found = false;

while(true)
{
    if (word[c] == '\0' && ( /* rather verbose condition, involving spaces */ )) { found = true; break; }

    if (para[i] == '\0') break; // found == false

    //...
}
m4ster_r0shi 142 Posting Whiz in Training

Are you familiar with functions? If not, it's a good time to start learning about them.

If not, maybe the instructor isn't ready to teach them...

Well, the OP said that this is not a homework assignment. Also,
this is not the first approach in this thread that uses functions.

So, is this something personal or what?

m4ster_r0shi 142 Posting Whiz in Training

Are you familiar with functions? If not, it's a good time to start learning about
them. As pointed out by others above, breaking the task into smaller steps
helps a lot. So, let's focus on building a line first. Take a look at these lines:

122222221
123333321
123444321

There is a pattern here. Each one of them consists of a left, a middle and a right part,
where the right part is the left one reversed and the middle part is a repetition of the
same number. Let's write them again, so that this becomes more obvious:

1 - 2222222 - 1
12 - 33333 - 21
123 - 444 - 321

This line also follows the same pattern:

111111111

It just happens that the left and right parts are empty.
Now, let's write a function that builds a line like this...

string line(int n, int i)
{
    // use the appropriate constructor to set the size for the left 
    // and right parts and properly initialize the middle part

    string   mid( /* ... */ );
    string  left( /* ... */ );
    string right( /* ... */ );

    // set the left and right parts 

    for (int j = 0; j < i - 1; ++j)
    {
        // remember that 1 + '0' == '1', 
        // 2 + '0' == '2', etc...
    }

    return left + mid + right;
}

Remember that we want …

WaltP commented: If not, maybe the instructor isn't ready to teach them... -4
m4ster_r0shi 142 Posting Whiz in Training

Geia sou Giannakh :D Kalws hr8es sto daniweb! Einai polu wraio na vlepw atoma apo thn patrida edw :)

(translation ->) Hello, John :D Welcome to daniweb! It's very nice to see people from home here :)

m4ster_r0shi 142 Posting Whiz in Training

Does anyone play DotA? What are your favourite heroes and item builds?