Clockowl 56 Posting Whiz

What archaic compiler are you using? Hehe. Get GCC, it supports (practically) all the C++ features + a bit more.

Clockowl 56 Posting Whiz

... size_t is a standard type (~100% of the time it's an unsigned int)... that's weird. Could you copy and paste what your compiler is saying please? :)

size_t is:
http://www.cplusplus.com/reference/clibrary/cstring/size_t/

Clockowl 56 Posting Whiz

Does this code compile for you?

int main(){
    size_t cols = 10;
    cin >> cols;
    size_t rows = 20;
    cin >> rows;

    char x[cols][rows];
    for(int i = 0; i < rows; i++){
        for(int n = 0; n < cols; n++){
            cout << x[i][n];
        }
        cout << endl;
    }


    return 0;
}
Clockowl 56 Posting Whiz

My goal is to create a program that plays Mahjong. I figured the algo would be a bit like this:

While there are blocks left {
Fetch new board
Recognize blocks //find 2 of the same images within the image.
Find free blocks //not *really* necessary: computer versions don't allow the non-free blocks to be clicked/removed, so the program can click away.
Check which ones are the same and remove those. //Will send input, but this part is covered. 
}

So obviously there are tons of algorithms for image recognition, but I was wondering if anyone knew the the simplest way of image recognition. What bubble sort is to sorting, this algo needs to be to image recognition. ;)

Thanks in advance,

Clockowl 56 Posting Whiz

So, what doesn't work? edges.open(); ? Double check the filepath please, hehe. Code looks okay, you won't need to clear it, unless errors occurred and you've recovered from them (or just want to reset them of course).

Clockowl 56 Posting Whiz

This'd work.

string filepath;
getline(cin, filepath);
ifstream fis(filepath.c_str());
Clockowl 56 Posting Whiz

Erm. I guess it can be compile in MSVC++. You can try to install MSVC++ Express and grab the platform SDK. Google is your friend. Can anybody else compile this code?

Clockowl 56 Posting Whiz

A class consists (most of the time) out of 2 parts: a definition and an implementation.

The definition defines the types and parameters of functions, as well as member variables. This is the header file.

The implementation gives code to the definition: it implements the definition.

Your assignment is to write an implementation given a specific definition: you're told what the objects should be able to do, but how they do it, how you implement those functions, is up to you.

Here is a simple example of a header file, it's implementation and it's use in a program. Note that the link uses void main() something you should never do.

http://functionx.com/cpp/examples/simpleclass.htm

Clockowl 56 Posting Whiz

is it possible to put a constructor into an array?

Yes, take a look here for an example: http://www.daniweb.com/forums/post847675-7.html

The size specifier for the array (base* [[b]3[/b]]) is not necessary, but it will make sure the array is of size 3 of course.

Clockowl 56 Posting Whiz

I really enjoy GTK+/gtkmm. :) Lots of demos and documentation.

Clockowl 56 Posting Whiz

Look up the functions and what they do, then put comments in there: it makes the code way more readable for yourself. If you can't figure out what a function does (which I doubt, using google and C(++) references) you can always ask.

Clockowl 56 Posting Whiz

Especially the part before. xD

Clockowl 56 Posting Whiz

What do you think the code is doing? Add some comments.

lancevo3 commented: Very helpful in attempting to solve my issues. +1
Clockowl 56 Posting Whiz

Header files such as string need to be included in the header file and in the .cpp file. We call these 2 files (header and .cpp) the definition of a class and its implementation when used to form a class.

If you want more help, ask more questions, but try to keep them specific.

Clockowl 56 Posting Whiz

No,

if(*n == ' ');
Clockowl 56 Posting Whiz

Example of inheritance using virtual functions:

#include <iostream>
using namespace std;

class base {
    public:
    virtual void func(){
        cout << "First level: Base class" << endl;
    }
};

class der1 : public base {
    public:
    virtual void func(){
        cout << "Second level: Derived class" << endl;
    }
};

class der2 : public der1 {
    public:
    virtual void func(){
        cout << "Third level: Second derived class" << endl;
    }
};

int main(){
    base* all_your_base[3] = {new base, new der1, new der2};

    for(int n = 0; n < 3; n++){
        all_your_base[n]->func();
    }

    return 0;
}
Clockowl 56 Posting Whiz

Thanks for that explanation. :) It makes sense.

Clockowl 56 Posting Whiz
class Client 
{
public:
	string name;
	Menu order;
	int table_number;
	string type;
	double bill;
	
	Client(void)
	{
		name="";
		table_number=0;
		type="";
		bill=0.0;
	}
};

This code lacks the virtual addClient table wants to use. Another note: is a table a client? If not, you shouldn't have inheritance, but perhaps composition.

Clockowl 56 Posting Whiz

Errr, ignore that last part. Sometimes I'm unclear.

Student student;
for(int subject = 0; subject < 4; subject++){
    string code;
    int cu;
    char pass_or_fail;
    inFile >> code;
    inFile >> cu;
    inFile >> pass_or_fail;
    
    //subject == loop variable
    subjects[subject].setCode(code);
    subjects[subject].setCU(cu);
    subjects[subject].setPF(pass_or_fail);
}

I meant something like that. That's the "input" loop. Now, as you can see, this one is for subjects, but you should also create one for students for their variables. Same goes for output. If you don't know how, first write the code for reading in 1 student, then simply loop that. ;)

Clockowl 56 Posting Whiz

No, student already has 4 subjects: use those.

Student::Subjects::setVar();
Clockowl 56 Posting Whiz

That sucks. But still, just loop the student array then, one time for input, one time for output. So no more extra variables representing members in class Student! ;)

Clockowl 56 Posting Whiz

You could create a function that accepts a reference to a student and outputs it's data?

void output_student(Student &stud){
//put the output code here
}
//....
int main(){
//loop each of your students here, one loop for reading in the data, the other one for outputting the data
}
Clockowl 56 Posting Whiz

Totally wrong approach buddy. Create 4 students, read out their data.

Example code:

cout << students[0].getVar() << endl;

Kinda like that.

Clockowl 56 Posting Whiz

The true or false return was from the earlier version, was to be removed, you're right.

The second defect, I hadn't noticed. But it is a defect for sure? New doesn't allocate any memory since it can allocate the whole block right? So, new doesn't allocate blocks of half the size you wanted, just because he couldn't get it all. New allocates either zero bytes or all the requested bytes? In that case, there will be no problem I think: Program can't allocate all memory, gets none, lots of memory free, plenty for the error message.

On the other part (using cerr), I'm not sure what to do about it. Maybe I'll reroute output from cerr to another ofstream in case I want to create a program with a GUI.

Apropos: That saves typing 7 chars. I think I can handle those. ;)

Clockowl 56 Posting Whiz

int main(int nNumberofArgs, char* pszArgs[]) {

Coders will have your head for not using argc and argv. xD

Clockowl 56 Posting Whiz

Does it only need to be in the output or also in the data itself?

Cout doesn't alter the data itself.

Consider what you want:

Skip 3 numbers
insert a hyphen
Skip 3 numbers
insert a hyphen

So, the string grows, you need to make the telephone number string bigger at the start and then alter it, else you'll get memory errors.

Try writing an insert function. (There are other ways to do it of course)

Clockowl 56 Posting Whiz

Ah, well I'll leave that exercise up for you now. You should be able to figure that out, if not, I won't be helping you for at least 8 hours: bedtime.

Good luck with the suffix and the phone numbers!

Clockowl 56 Posting Whiz

Depends on what there is to fix with the suffix. :)

On a side note: 300! Ahem. *clears throat*
TONIGHT
WE DINE
AT DANIWEB!

Clockowl 56 Posting Whiz

Hmz, okay. There's no way of catching the exception "going on" ? I can only check whether there's one (from anywhere in the code?), but not which one?

Clockowl 56 Posting Whiz

Good luck with the assignment, don't forget about the STL! (It has a queue, of course you can't use that, but it has plenty of other useful containers and algorithms).

Clockowl 56 Posting Whiz

If you're standing in queue line at the grocery shop, does the LINE look like a tree, with intersections and such, or more like an array of (possibly annoyed) customers?

I sure hope it doesn't look like a tree.

Clockowl 56 Posting Whiz

Hey guys,

How do you handle exceptions in your programs? For instance, I have this function:

bool load_file(const char *filepath, std::string &dest)
throw (std::bad_alloc, std::runtime_error) {
    using namespace std;

    ifstream file;
    file.open(filepath, ios::binary);
    if (!file.good()) {
        throw runtime_error("Couldn't open the file");
    }

    //get filesize in bytes from ifstream
    //seek end, get pointer, rewind
    file.seekg(0, ios_base::end);
    size_t file_size = file.tellg();
    file.seekg(0, ios_base::beg);
    if (!file.good()) {
        throw runtime_error("Fatal error while getting filesize.");
    }

    //read file in string from ifstream
    //allocate array, read file in array, set the term. null byte, set string to array

    char *file_content;
    try {
        file_content = new char [file_size+1];
    } catch (bad_alloc &memException) {
        cerr << "Probably went out of memory while allocating " << file_size+1 << " bytes!" << endl;
        file.close();
        throw;
    }

    file.read(file_content, file_size);
    file_content[file_size] = '\0';
    dest = file_content;

    //clean up
    //close file, free array
    file.close();
    delete[] file_content;

    return true;
}

How would I handle the throw at line 7? Only with a try-catch block, or is it also possible to call the exception.what() in the terminate function?

Here's the rest of the program, I'd like to make my terminate function show what went wrong, to really have 1 central place for all the fatal errors.

#include <iostream>
#include <fstream>
#include <string>
#include <new>

#include <stdexcept>

/* load_file(filepath, destination)

   -Returns whether it succeed or not. True meaning succeeded.
   -Takes a path and writes to a std::string, completely memory safe.
*/

bool load_file(const char *filepath, std::string &dest)
throw (std::bad_alloc, std::runtime_error) {
--------------------cut …
Clockowl 56 Posting Whiz

Oh I'm so sorry! I thought the addresses started with a alphabetic char (like Shady In 10) But they don't! Sorry sorry sorry.

Here's your fixed function, study it a bit, but not too long: it's C, not C++ we're coding here. :( You're better of using std::string.

void fixAddress ( char *a ) {
    //find first alphabetic char
    //this loops while *a != alphabetic char or we reached the end of the array.
    while(*a != NULL){
        if(isalpha(*a)) break;
        a++;
    }

    //make the first alphabetic char uppercase
    *a = toupper(*a);

    //go to the next char
    a++;
    //loops till the end of the array, sets every char to lowercase
    while(*a != NULL){
        *a = tolower(*a);
        a++;
    }
}

you need to #include <cctype> for the isalpha() function. :)

Clockowl 56 Posting Whiz

Your file would be helpful as well, just to make sure.

Nevermind, grabbed it from the site:

JOHN MCCARTHY  3245 HILLCREST DR 8157359091  Mercedez_bEnz, S500   85800.00
Levy, MATTHEW  10 Shady ln       3126883568  chevrolet, MALIBU     16750.00
james lancaster1206 Hillgrove Ave9017492475  BUICK, lesabre        24230.00
Gates, Dennis  2066 Woodland st  2136548521  AM_GENERAL, HUMMER_4DR94529.00
Randy kraft    1721 Grant Hwy    4093651514  linCOLn, TOWN CAR     48610.00
seymore, BETH  3001 BLACKHAWK ST 3076567465  PONTIAC, BONNEVILLE   32560.00
Forest Pierce  24 Wilson Rd      2178524582  cadillac, escalade    50285.00
Knoll, Bradley 3500 Brayton Place7012689511  Mercury, Cougar       16300.00
Joyce More     23 Greenwood dr   7486308523  TOYOTA, AVALON        30405.00
Kingston, shari5110 glidden rd   5202314583  DODGE, INTREPID       24975.00
JOSEPH HUMPHREY19 sitka ln       2127651591  VOLKSWAGEN, beetle    16850.00
clark, Aaron   4381 first st     9158659899  porsche, 911          81500.00
Gail Holtman   3311 Taylor rd    2136754142  volvo, S80            48750.00
Spencer, Teresa56 lucinda Ave    3126533653  BUick, regal          28000.00
Clockowl 56 Posting Whiz

OK maybe that code doesn't compile, a few missing brackets, whatever,

Don't be so careless. Programming is a precise task, I fail it often enough, but you're just making a joke of it now.

The code I posted should work and contains your answer. Analyze it, compare it to your code and reply with the differences you notice if you want to learn.

Clockowl 56 Posting Whiz

Err, post your complete code? I'm getting curious now. xD

Clockowl 56 Posting Whiz

It doesn't compile in MinGW's GCC. Looks like MSVC code?

I'm getting these errors:

=|
sdvrp.h|18|warning: ignoring #pragma warning |
sdvrp.h|222|warning: no newline at end of file|
genius.cpp||In function `double genius(route*&, Nb&)':|
genius.cpp|732|warning: comparison between signed and unsigned integer expressions|
genius.cpp|733|warning: comparison between signed and unsigned integer expressions|
genius.cpp|736|error: no matching function for call to `std::vector<node*, std::allocator<node*> >::erase(node**)'|
vector.tcc|108|note: candidates are: typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = node*, _Alloc = std::allocator<node*>]|
vector.tcc|120|note:                 typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, __gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = node*, _Alloc = std::allocator<node*>]|
||=== Build finished: 1 errors, 4 warnings ===|

Maybe someone else can compile it tho.

Clockowl 56 Posting Whiz

err, sorry

Change that for loop, init part to int i = 1, ofc. xD

like this:

void fixAddress ( char *a )
{
  a[0] = toupper(a[0]);
     for (int i = 1; i < strlen(a); i++)
     {
         a[i] = tolower(a[i]);
     }
     
}

PS: I take it that you do understand how this works right?

Clockowl 56 Posting Whiz

Hurr, multiple errors.

That code shouldn't compile!

#include <stdafx.h>
#include <iostream>

using namespace std;

int main() {
    int num;

    cout << "Enter trees = ";
    cin >> num;


    float *trees = new float[num]


    for (int i = 0; i < num i++) {

        cout << "\nEnter tree " << (i+1) ;
        cin >>tree[i];
    }

    for (int i=0; i<num i++) {
        cout << tree[i] << i+1 << endl;
    }

    return 0;
}
Clockowl 56 Posting Whiz

Oh it does you no good, but you can't really check for !file, since file would be.. something. Although it "worked", maybe by accident.

Anyway, Could you hardcode the path, "C:\test.txt", and put the file up here? I'll test it.

Also, on what OS/compiler are you? Just to make sure.

Clockowl 56 Posting Whiz

Paste your code please.

Clockowl 56 Posting Whiz

So this should not be in a loop?

for (char *p = a; p!= fixPtr; p++)
     {
         *p=toupper(*p);
     }

Why not do something like:

Set first letter to uppercase.
Rest to lowercase

with

void fixAddress ( char *a )
{
  a[0] = toupper(a[0]);
     for (int i = 0; i < strlen(a); i++)
     {
         a[i] = tolower(a[i]);
     }
     
}

Which only works if a is null-terminated of course, but I'm guessing it is.

Clockowl 56 Posting Whiz

Wait, doesn't the fstream constructor *always* create something? Check if file.good() is true.

If the constructor is not successful in opening the file, the object is still created although no file is associated to the stream buffer and the stream's failbit is set (which can be checked with inherited member fail).

Oh and, don't open it twice. In the constructor OR with fstream.open(), not both.

Clockowl 56 Posting Whiz

So, what doesn't work?

Check here for more info on templates:
http://www.cplusplus.com/doc/tutorial/templates/

Clockowl 56 Posting Whiz

Oh hey look, it's free knowledge!

http://en.wikipedia.org/wiki/Sorting_algorithm

Clockowl 56 Posting Whiz

Hurr, it might be a really stupid "error".

One time (at band camp, xD) I was trying to open a file from an app I wrote in Code::Blocks on windows. So I put that file in project/bin/debug/, but code::blocks launched it in project/, so it couldn't find the file.

Try to open an absolute path like "C:\test.txt".

Clockowl 56 Posting Whiz

Yeah, but keep in mind he didn't design the functions himself, his prof did it for him. He needs to use these functions, unaltered, I think.

Clockowl 56 Posting Whiz

I accept all that you're saying there, and good point about the multi-core processors, though even they would not cause a problem in this case.

On my dualcore processor, 2 cores where in use and it indeed didn't give any errors as stated earlier. This is on Windows XP x64.

Clockowl 56 Posting Whiz

Decide the interactions. What controls the stones? How will they control the stones? Do more objects need to know the stones' places? All that stuff. Maybe read some tutorials on OOP, they can get you going. :)

Clockowl 56 Posting Whiz

I didn't say it isn't random, I just said he can't ensure that every element moves at least once ;)

Well technically, they moved twice. But I catch your drift: it's not guaranteed that all the values will be at different indexes from where they started. Anyway, your first argument was pretty good, nobody would ever "switch" card 1 with card 1, so... I think that's a pretty good algo for randomizing stuff.

But, hey, we're C++, why not use STL's random_shuffle? Works on every STL container, suits the job just fine.

Here's a nice example: http://www.cplusplus.com/reference/algorithm/random_shuffle/