Tumlee 42 Junior Poster in Training

Is this memory efficient to split things up for developer "ease-of-use"?

Even if it wasn't, it doesn't matter. Code maintainability and readability is a lot more important than shaving off a few bytes here and there. Your time as a developer is a worth more money than a few processor cycles.

Tumlee 42 Junior Poster in Training

He means this sounds like a homework assignment, and we don't do those for people. You actually have to show some sort of an effort towards solving the problem.

Tumlee 42 Junior Poster in Training

NathanOliver: There is actually a getline() for std::string as well. istream& getline (istream& is, string& str);

Tumlee 42 Junior Poster in Training

Your usage of one-letter variable names, which are all declared at the very top of your main() function, has your program nearly impossible to read, let alone debug. You need to provide descriptive variable names if you want your stuff to be self explanatory. Do you seriously think it's good practice to have a variable called count and another one called count1? How on earth do you expect not to get those confused? I'm not suprised at all that you have an untrackable bug in your program.

Tumlee 42 Junior Poster in Training

You've got the right idea, but overloading really isn't polymorphism at all.

Tumlee 42 Junior Poster in Training

The while statement is a loop that contininues to execute until some condition is met.

I think you meant to say a while statement is a loop that continues to execute while some condition is met.

Tumlee 42 Junior Poster in Training

Years ago I picked up the habit, I don't know where from, of always using

#define NUL char(0)

for 0 terminators in ASCII strings, and NULL for pointers.

I wouldn't recommend that at all, and to be honest I don't see the point of using macros for such things anymore in C++. If you want an int to be zero, use 0. If you want a char to be a terminator, use '\0'. If you want a null pointer, use nullptr (or use NULL if you're using C or have to compile for something older than C++11). To me, it only makes sense to write exactly what you mean when writing code.

Tumlee 42 Junior Poster in Training

Are struct names supposed to be defined somewhere else?

Yes. When you declare a variable that is an instance of usb_device_id, you must first tell the compiler somewhere else what a usb_device_id is. If you have already written a declaration of this struct, we might have to see it so we can further identify the problem.

Tumlee 42 Junior Poster in Training

The problem is that by declaring a function in Derived that is the same name as the virtual function you declared in Base, you are actually hiding the original function that you declared in Base. These are little-known rules but they are rules nevertheless. When you have a function that takes two ints instead of one, as far as the compiler is concerned, the virtual function that only takes one argument no longer exists.

You can actually circumvent this behavior by adding using Base::SomeFunction; in the declaration of Derived.

Tumlee 42 Junior Poster in Training

No. It's unsafe, because as I stated before, there is no guarantee that the buffer will fit what you type into it. As you have it right now, strg will hold nine characters plus the terminating character ('\0'). If the user types a string that is ten characters or more, your program may behave erratically or it may crash, either instantly or somewhere down the road.

Instead of using cin >> strg;, you should use cin.getline(strg, 10); in this case, which will read a line of text that the user types, and makes sure not to fill your array anywhere past those ten characters that you can hold.

Tumlee 42 Junior Poster in Training

C-style strings don't work like that. A variable of type char* is a pointer, and as such it actually has to point to a valid memory location before you can modify information in it. I advise against using char* with cin anyway because there isn't a guarantee that what you input will actually fit in the buffer.

You have two possible solutions to this problem:

1) Use std::string for your string instead.
2) Turn strg into an array instead of a pointer, and use cin.getline(strg, XXX) where XXX is the length of your array.

Tumlee 42 Junior Poster in Training

Although logically there should be a guarantee here that your function will reach a return statement, the java compiler doesn't seem to see it that way. I think there are two possible solutions:

1) Add an extra return statement that just returns some arbitrary value to appease the compiler.
2) Rewrite your logic as an if-else chain, like so:

public static int func(int a,int b,int c) {
    if((a>=b)&&(a>=c)) {
        return(a);
    }
    else if((b>=a)&&(b>=c)) {
        return(b);
    }
    else {
        return(c);
    }
}

This makes it much easier for the compiler to be able to tell that your function is guaranteed to return a value.

Tumlee 42 Junior Poster in Training

Usually, people just put the main() function in main.cpp (and sometimes a function or two that will only ever be used by main()), and leave other functions in other files.

The place where you actually "flesh out" the function, as you put it, is called the "implementation" of the function (at least where I come from). Implementations of functions other than main() belong in other .cpp files. How you organize those .cpp files depends on how you're writing your program, really.

When you're doing object oriented programing, it's common to see a class get it's own header and it's own matching .cpp file. For example, if I have a class called Ball, I will put the declaration of the class in "Ball.h", and the implementations of its member functions in "Ball.cpp".

Generally this is how it goes, even outside of object oriented programming. If you have a bunch of functions that deal with crunching numbers for geometry, perhaps you should throw those into a "geometry_math.cpp" and "geometry_math.h".

Tumlee 42 Junior Poster in Training

A function that prints something and then returns an integer is a bad example to try and understand the difference between a void function and a function that returns a value. Let's see if this clears things up, and please read the comments to understand what's going on here:

#include <iostream>

using std::cout;
using std::endl;

//Note that, by declaring a function as float, we specify that it
//RETURNS a float as its output. It doesn't matter what type of argument we
//feed it.

//This particular function just cuts an integer in half and returns it as
//a float.
float half(int input)
{
    return input / 2.0;
}

//This function down here is void. It doesn't return a value, it can't be used
//as a value in an expression. You just call it, and it does something.
void printstuff(const char* stuff)
{
    cout << stuff << endl;
    return;
}

int main()
{
    //Because half() returns a value, we can actually USE it in an expression,
    //just like we'd use any other variable or value.

    //Because half() returns a float, myresult must also be a float (or at least
    //something that can be converted from a float)
    float myresult = half(3);
    cout << myresult << endl;

    //The printstuff() function, having nothing to return, just gets called on
    //a line all by itself.
    printstuff("Hello, void!");

    return 0;
}
bguild commented: Going the extra mile to be helpful! +6
Tumlee 42 Junior Poster in Training

You can use whatever compiler you want. Obviously, you would have to link in whatever libraries you are going to use for the graphics, sound, and timing (something like SDL, DirectX, etc.) If you're doing this all through the command line, you'll have to google the exact command line switches you would use to do that, because I personally use an IDE for all that stuff anyway.

The "game engine" is basically the code you've written that ties all those timing, graphics, and sound functions together in such a way that they can be used to build a game (I'm sure there are plenty here who would disagree with me on definition). For example, the main loop that waits a specific period of time and skips frames if the game is falling behind would be part of the "engine". It could be just a collection of .cpp and .h files that you include with your project, or it could be a library you've put together beforehand.

Tumlee 42 Junior Poster in Training

The physics engine is actually the easiest thing you can possibly do when designing a 2D game like you describe, especially if the framework of the game engine is written in such a way that time is cut up into "ticks" and the physics updates on each of these ticks (as opposed to writing the graphics/sound portion which 99% of the time requires you to use somebody else's library). Unless you're going to be doing crazy stuff like rotating boxes crashing into one another and having to deal with center of masses, etc, then you only need to have a basic knowledge of physics in order to do this sort of thing.

Each moving object will probably have to have its own position variable, both x and y. They will probably have their own velocity value, both x and y. If it's a falling object, increment the y velocity by a constant amount each during physics step to apply gravity. After that, you'll increment the position value by the object's velocity to move it, and do some collision detection to make sure you're not going through objects. This is basically what you'll be doing.

We don't know how much you have done so far, but what you'll be doing also depends on if you're writing a simple game engine from scratch or using something written by somebody else.

Tumlee 42 Junior Poster in Training

You're declaring all these variable as extern, but they don't seem to actually exist anywhere. When you say extern std::string nomEnnemi;, for example, you're not actually declaring a variable, but simply promising the compiler that it exists in another file.

You actually do declare these variables, but you only do it in a scope that's local to the InitVariable::InitialiserVariable() function. Those variables don't actually exist outside of this function. Moving these declarations outside of the function will certainly solve some of your problems.

Once you get past this problem, there will be a few other errors, particularly where you are trying to access member data that belongs to the Personnage class in a function that belongs to the SystemeBattaille class, but I don't actually know what your code is supposed to do, so I'll leave you to figure those problems out.

Tumlee 42 Junior Poster in Training

In the case that you've presented here, sizeof(a) is resolved during compile. The only time it's resolved during runtime is when you're dealing with C99's variable length arrays.

The reason the above code works is that the number of bytes taken up by an int is always going to be the same, no matter what number is being stored in it. If you're compiling for a system where sizeof(int) is four bytes, then it's going to be four bytes no matter what you do to it.

Tumlee 42 Junior Poster in Training

To set the command line parameters in Code::Blocks, you go to Project -> Set programs' Arguments..., and if your version is not bugged like mine is, you should see a text box where you can enter command line parameters to be used when running your various build targets. Normally, I'd tell you to RTFM, but I've experienced the nightmare of trying to navigate the CodeBlocks wiki myself so I really don't blame you.

A forewarning, though. By default, your program will actually execute from your main project folder, and will therefore have trouble finding certain files in the same directory as the executable. You might have to circumvent this by doing "-e -f bin/somefile" instead of "-e -f somefile".

Tumlee 42 Junior Poster in Training

In the future, if you have a new question you should create a new thread. Otherwise, people will skip over your thread thinking it's solved.

The crash is located on the line where you call fclose(fpOUT). Upon further inspection, it appears that you never actually open fpOUT so why it's not crashing earlier is actually a mystery to me. Your mistake appears to be on this line:

if (mode != 'N' && (fpIN = fopen(inFileName, "r")) != NULL && (fpIN = fopen(outFileName, "w")) != NULL) {    

Not how you're setting fpIN twice. One of those should be fpOUT. If you're wondering how you can find this information yourself in the future, here's what to do if you notice your program crashing, since you're using Code::Blocks.

You can access your debugger by first switching your build target from 'Release' to 'Debug', and then at the menu at the top you go to 'Debug' and click 'Start'. When your program crashes, it will point a yellow arrow right at the line where it crashed.

Tumlee 42 Junior Poster in Training

Clarifying what Adak said, here's what you should know:

The & symbol (address-of operator) will return the address of a variable (where it is stored in memory). If you have declared an integer called foo, then &foo would be its address.

When you're dealing withprintf(), you only really need to know the values of these variables. You don't need to know where they're being stored, because you only really care whether foo is a 3, a 12, or whatever number. You will never use & in printf() unless you plan on printing out raw memory addresses, which you will almost never do.

Then scanf() function actually needs to modify your data. In order for it to do this, having a value isn't enough, it actually needs to know where your variable is stored in memory so scanf() can modify it. This is why scanf() requires an & sign for most types.

The only exception to this rule is strings. A string esssentially is a memory address that points to the first character in a group of characters, so neither printf() nor scanf() take the & symbol in this case.

Tumlee 42 Junior Poster in Training

When you're using range-based for loops, the variable you declare to the left of the colon must be at type that refers to an element of the array or list on the left. Take the following code:

#include <iostream>

using std::cout;
using std::endl;

int main()
{
    int array[4];

    for(int& element : array)
        element = 3;

    for(int element : array)
        cout << element << endl;

    return 0;
}

The reason the second loop works is obvious --- it's an array full of ints, and element is declared to be an int. The first loop is also acceptable because an int& (reference to an int) can also be used to directly refer to (and modify) elements in the array. If you try to do the following:

for(int* element : array)
    *element = 3;

You will end up with a compiler error. This is because array is an array full of ints, not int*s. Although you could theoretically use pointers to look through an array, this isn't what range-based for is supposed to do. This is essentially why your code is resulting in a compiler error --- the compiler doesn't treat pointers the same way it treats references when it comes to range based for.

Vasthor commented: thankyou +2
Tumlee 42 Junior Poster in Training

You're trying to grab the lowest five values in your array, right? What would really help you is if you commented your code, so you're forced to explain your thought process to yourself. That way, it will become more obvious why your code doesn't work.

The reason your program is "skipping values" is because, before you iterate through all the entries in the array with the loop for(int i = index, limit = array.length; i < limit; ++i), you're incrementing the starting index with the line index++;. Because i is initialzed to index, what's happening is that you're skipping the first element of your array the first time around, and then you're skipping the first and second elements of your array the second time around, and so on.

What purpose does the line min = array[x]; serve? You need to be asking these sorts of questions.

Tumlee 42 Junior Poster in Training

The only thing you'll need to do here is to reset total to zero at the beginning of your loop. That action alone will fix your code.

You're missing a few brackets and others aren't correctly placed.

There are no missing brackets here, and the brackets aren't placed incorrectly at all. What he's using is an indentation style known as K&R styling, which is a fairly common way of writing C, C++, and even Java code.

Tumlee 42 Junior Poster in Training

The reason it's skipping is becuase char is actually a signed type, which means that it includes positive and negative numbers. This means that, when trying to interperet a char as an 8-bit integer, its effective value range is actually -128 to 127 instead of 0 to 255. When a character with an ASCII value higher than 127 goes into this if statement, your code is actually reading it as a negative value (147, for example, gets read as -108), which is always going to be less than 122.

To circumvent this behavior, all you need to do is typecast the character into an unsigned char, like so:

if((unsigned char)userInput[value] > 122)
{
    //Code...
}
Tumlee 42 Junior Poster in Training

The reason your program is behaving so unpredictably is because you are not initializing the variable res in your seno() function, nor are you initializing sin1 in your sen() function. Because you are using the values of these variables before initializing them, you are invoking undefined behavior. I could go on a long, detailed explanation of why it sometimes works, and why it sometimes doesn't work, but it's more important to simply fix the code.

When you declare sin1 and res, set them equal to 0.0 and it should work.

Tumlee 42 Junior Poster in Training

Here's how I comment your code. Please note that, according to your code, 2 is not a prime number. You might want to fix that.

import java.util.Scanner; //This line helps the compiler find the class file Scanner. 
public class PrimeNumber{ //Defines a class called PrimeNumber
public static void main(String args[]){ //Declaration of the main method of the program.
int n; //This line declares an integer variable called n.
Scanner Prime = new Scanner(System.in); //Declares a scanner, a class that takes input from the user.
System.out.println(" Please enter a number: "); //Prints the phrase " Please enter a number: " to the screen on its own line.
n = Prime.nextInt(); //Grabs the very next integer the user types, and stores it in the variable n.
if (isPrime(n)) //An if-statement that calls isPrime() to check if n is prime.
System.out.println("The number is prime.\n"); //Prints the phrase "This number is prime." to the screen on its own line, and then skips a line.
else    //Tells the program to execute the next line of code, in case n isn't prime.
System.out.println("The number is not prime.\n"); //Prints the phrase "This number is not prime." to the screen on its own line, and then skips a line.
}
static boolean isPrime(int n) { //Declares the isPrime() function, which returns true if the parameter 'n' is prime, and false otherwise.
if (n%2==0)return false; //Use the modulus operator to determine if n is divisible by two, in which case it is even and therefore not prime. This …
jalpesh_007 commented: you're right.. +3
Tumlee 42 Junior Poster in Training

You're already halfway there when it comes to understanding this line, then. For this code to make sense, src has to be a pointer to a pointer type, such as char**, and offset has to be a pointer type, such as char*.

What this particular line of code is doing is saying "Make the memory at the address pointed to by offset equal to the value at the address pointed to by *src (src itself being an address that points to that address), and then increment *src so it points somewhere else." It sounds like a mouthful, but that's how it works.

Tumlee 42 Junior Poster in Training

You're not accessing an array wrong, you're causing a stack overflow because Solve() keeps calling itself over and over again when the parameter is zero

Tumlee 42 Junior Poster in Training

When you push a char* into a vector, you're not adding the actual characters to the vector, but rather a memory address that points to the characters. What's probably happening in your case is that file.cFileName (a memory address) remains the same, so you keep pushing the same value over and over again into temp. However, the actual characters pointed to by file.cFileName keeps getting changed every time you call FindNextFile().

The way you're going about this is actually dangerous, because if file.cFileName ever had to change locations, you program would instantly crash the moment you tried to access to old memory. A better way to go about this is to have the type of temp be a vector of string rather than of a vector of char*.

vijayan121 commented: Yes. +14
Tumlee 42 Junior Poster in Training

Let's go through this problem by problem.

1) You got completely confused while naming your member variables. As pyTony said above, in student.h:

    int newid;
    string newname;

Should be changed to:

    int ID;
    string Name;

To finish fixing these naming conflicts, change Student::Student(int ID, string Name) to Student::Student(int newid, string newname) in student.cpp.

2) In main(), you are calling student.setStudentID("1234");. When you put quotes around something, you're turning it into a char*. This function is supposed to take an int. Remove the quotation marks on this line and it should work.

3) In Student::display(), some of your chevrons are backwards when using cout. Flip those around.

Tumlee 42 Junior Poster in Training

and you can use void main() there is no need of making it int.

Disregard this advice, Hitman.

then what is the problem???

This should explain why void main() is not only wrong, but it can also be dangerous: http://users.aber.ac.uk/auj/voidmain.cgi

Otherwise, the above code is more or less correct (I would have organized this entire program a bit differently).

Tumlee 42 Junior Poster in Training

Use a new version of the compiler with the bug fixed

I suggest this one, because ideally a compiler shouldn't crash no matter what you feed it.

Tumlee 42 Junior Poster in Training

You're probably creating a text file, but then you're just naming it like a PDF. Just changing the file extension doesn't change the data inside the file, it's still just text. That would be like calling your chicken a pig, slaughtering it, and expecting it to taste like pork.

I didn't even know it read pdf..

It doesn't. It can, however, read a text file renamed so it says ".PDF" at the end.

Tumlee 42 Junior Poster in Training

SFML still has some maturing to do. The last time me and my friend tried to make something with it, it turned out it didn't even support certain computer architectures. In the meantime, I suggest using SDL, and it's extensions, SDL_mixer and SDL_image, to make a game. With the proper knowhow, you can make a full 2D game with sound, music, and graphics.

Tumlee 42 Junior Poster in Training

This is definitely one issue:

printf("max = %d\n", max);
printf("min = %d\n", min);

max and min are not integers, they are functions that return integers, so these lines of code don't make any sense. I'm not even sure how you got this to compile, but your program is probably printing out the memory addresses of your min() and max() functions.

You're not even recording any of your grade's values anyway, so it will be impossible to know what the maximum and minimum grades are the way you wrote your code.
HINT: You need to recalculate the minimum and maximum values inside your loop.

Tumlee 42 Junior Poster in Training

"Just make an empty method" I would need a little help. How to do it ?
(I know it sounds stupid but I haven't touched c++ in 10 years...)

You would just make a function put nothing in the brackets except for a return; statement in this case. If the function was non-void you'd probably want it to return an actual value. The following should probably work:

void CheckFileNames::RecordAsset(const MaxSDK::AssetManagement::AssetUser& asset)
{
    return;
}
Tumlee 42 Junior Poster in Training

If you want to create a program in C or C++ with graphics, you should first switch to a modern IDE (like Code::Blocks or Visual C++). From there, you should learn how to a library like OpenGL, SDL, DirectX, or something similar.

Tumlee 42 Junior Poster in Training
struct{
const int EAST = 0;
const int SOUTH = 1;
const int WEST = 2;
const int NORTH = 3;
};

Who in God's name would use a struct like that? That is not what structs are there for.

The enum keyword is for where you want to have different, related constants enumerated without having to use #define on everything. Logically, it should only be used when the number behind that constant has no real meaning. (For example, nobody should care that direction_north is 2, or 3, or -45, because the code should only really refer to it as direction_north ). If you have to refer directly to a value like that, you're probably using enum incorrectly.

Here is an example of how I used an enum in a game I am currently programming.

//enum for statuses returned by loadgame()
enum loadstatus_t
{
    load_success,     //Indicates that the savegame was successfully loaded.
    load_nofile,      //Indicates the save doesn't exist.
    load_badversion,  //Indicates the save is from too new or old of a version.
    load_smallscreen  //Indicates the user's screen dimensions can't fit the save file on screen
};

A struct should be created when you have several variables that 'go together'. For example, you can have this mess:

float redapple_weight;
float redapple_diameter;
int redapple_price;
bool redapple_isrotting;

float greenapple_weight;
float greenapple_diameter;
int greenapple_price;
bool greenapple_isrotting;

float crabapple_weight;
float crabapple_diameter;
int crabapple_price;
bool crabapple_isrotting;

See how much of a mess that is? You basically have to copy-paste a lot of …

Tumlee 42 Junior Poster in Training

I really do like programming, it's just that the problem solving part is difficult for me.

I have devastating news for you.

I forgot to mention that I'm relatively new to C++, and I have no idea what most of that means :p

Don't fret. I've been using C++ for five years and I still don't know what most of that code means.

It was on a quiz that I had already done, and I couldn't figure out the answer.

There's no "the answer" when coding. There's always multiple different ways to do the same thing, depending on how you attack the problem. You'll see my version is vastly different than thines01, and probably different than how WaltP would do it.

Here's the way I would have done it. No templates, two loops, can be easily converted to use vanilla C. Portable. Delicious.

int main()
{
    int input;
    cout << "Input a number." << endl;
    cin >> input;

    if(input < 1 || input > 9)   //Bounds checking...
    {
        cout << "Sorry, must be between 1 and 9." << endl;
        return 0;
    }

    //Print square; the closer to the edge, the smaller the number.
    for(int line = 0; line < SQUARESIZE; line++)
    {
        for(int ch = 0; ch < SQUARESIZE; ch++)
            cout << min(min(line+1, ch+1), min(SQUARESIZE-line,SQUARESIZE-ch));

	cout << endl;
    }

    return 0;
}

"Problem solving" isn't something you can really learn on Daniweb or in a C++ class. That's just something that takes practice.

Tumlee 42 Junior Poster in Training

In the comments you'll see some potential problems with this code.

#include<stdio.h>
#include<string.h>
int main()
{
    //You're intializing a two dimensional array with a one-dimensional initializer.
    //This may cause problems.
    char a[4][4]={'j','u','s','t'};
    int i,l,j,k,b=4,n; //If b is the number of characters, why not name it numchars or something like that?

    //Asking the user to enter a string and not giving him a chance to input.
    printf("Enter the string");
    printf("\n");

    //What's the point of this loop? It only executes once while i is zero.
    for(i=0;i<1;i++)
    {
        for(j=0;j<b;j++)
        {
            printf("%c",a[i][j]);
        }
    }

    printf("\n");
    n = b;
    
    //Huh? i==0? This is probably your problem. i is never changing in this loop at all.
    //b also never changes, so your loop will go on forever.
    for(i=0;i<b-1;i==0)
    {
        //Even if i was properly incrementing, you never set all 16 the values in the
        //array. You'll be reading from uninitialized garbage when i is greater than zero.
        for(k=n-1;k<b;k++)
        {
            printf("%c",a[i][k]);
        }
        for(j=0;j<n-1;j++)
        {
            printf("%c",a[i][j]);
        }
        printf("\n");
    //Because your loop is infinite, n becomes a negative number, forcing this value
    //into k will force your program to read a negative index in the array, crashing
    //your program.
        n--;
    }
    //ALL programs should have a return statement at the end of main().
    //In most cases, you want to return 0;
}
Tumlee 42 Junior Poster in Training

...by this I mean you should never use a break statement in anything other than a switch

I agree with most of the stuff you said, but certainly not this. You should avoid using a break statement in for loops when you can, but there are an awful lot of cases in the real world where it's more clean or even more efficient to use break statements in for loops.

Ancient Dragon commented: agree +17