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

When used correctly, polymorphism is easily the most useful feature in all of C++. It's more particularly useful when you start getting into game design, where you often have large linked lists of actors, all belonging to different subclasses but all needing to behave differently from one another. In such a case, you'd often give them different "thinker functions" so they can reliably execute even though the programmer doesn't have to keep track of which actor belongs to which class.

#include <iostream>

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

//The parent class upon which two polymorphic classes
//will be defined, dog and cat.
class animal
{
    public:
        bool tailwagging;

    //This is a polymorphic function. What this line does is
    //tell the compiler that all subclasses that inherit from
    //"animal" will have an is_angry() function that returns a bool
    //and takes no arguments.

    //This " = 0" at the end tells us that the "animal" class itself
    //has no is_angry() function, so "animal" is an abstract class.
        virtual bool is_angry(void) = 0;
};

//A cat class that is an animal. It has its own definition of whether it's
//angry or not, so it should have its own implementation of the "is_angry()" function.
class cat : public animal
{
    public:
        virtual bool is_angry(void)
        {
            //If a cat's tail is wagging, it's angry.
            return tailwagging;
        }
};

//A dog class that is an animal. We use different logic here for determining whether
//or not it is angry. It's still an animal, though, so it will …
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

My apologies; the phrase "I have this code in C" threw me off and led me to beleive the OP was feeding the posted code directly into GCC.

Tumlee 42 Junior Poster in Training

The syntax in this program you've written is completely wrong. It doesn't even appear to be real C code. What do you think the lines letter [a-zA-Z] and digit[0-9] do? What's with the two percent signs on the next line?

Tumlee 42 Junior Poster in Training

Can you provide us with the code you have for the registers() function? Perhaps the reason you're getting an extra percent sign is because your function is tacking it on automatically. If it's not, I would have a reason to believe there's something wrong with your compiler because when I do printf("%%%s", "eax"), I'm getting the expected output of "%eax".

Also, C90 isn't a compiler, it's a language standard from around 1990. We're on C11 now.

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

argv is not a char, it's a pointer to a pointer to a char, so the comparison argv != '\0' makes no sense. You really shouldn't be modifying argv directly by incrementing it anyway.

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

Your variables will only be reset to zero if you set them to zero yourself, or if you call a function that sets those variables to zero. I don't know what your "LevelUp" functions do, because you never provided them in this thread, but they shouldn't really affect the variables being passed to them unless you're passing-by-reference instead of by value.

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

You forgot to post Personnage.h so we might not be able to help you troubleshoot your problem. Can you at least tell us which variables it's complaining about being undefined?

Tumlee 42 Junior Poster in Training

Where am I going wrong?

If you had given your variables descriptive names so you could easily read through what your code is doing, or at least provided comments illuding to your train of thought when writing this program, you likely wouldn't have to ask us this question.

Tumlee 42 Junior Poster in Training

On line 43, while(stillguessing == true); you have actually results in an infinite loop if stillguessing is true, because of the semicolon. Remove the semicolon to fix it.

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

thats why i am using memset which fails.

This isn't what memset() is supposed to be used for. It does byte-by-byte setting to a specific value. You're going to have to use the loop.

Tumlee 42 Junior Poster in Training

You'll have to write code manually that will sort the array. You can use Google to find various sorting algorithms you can use.

Tumlee 42 Junior Poster in Training

That was a valid program, if written 30 years ago.

If by "valid", you mean "it compiles". The void main() means it's techincally not legal C++.

You must use either std::cout or issue the following statement before using cout: using namespace std;

I personally use like to include only the parts of the std namespace that I want to use, so I can use what I want without getting naming conflicts from unrelated parts of the namespace, like so: using std::cout;

So, add the line return 0; before the end of the main function.

I think the standard says that main() will return 0 automatically.

Tumlee 42 Junior Poster in Training

More than likely, your program will terminate immediately. Sometimes it will keep going, overwriting memory that you're not supposed to will almost certainly cause your program to malfunction somewhere later. My advice is that you're not supposed to do it.

Tumlee 42 Junior Poster in Training

There is no difference, functionality-wise between char** argv and char* argv[]. It's all a matter of preference.

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

Uniform initialization refers to this, correct?

class xypoint
{
    public:
        float x;
        float y;

        xypoint(float xx, float yy) : x{xx}, y{yy}
        {
        }
};

xypoint returnpoint(void)
{
    //Equivalent to "return xypoint(3, 4);"
    return {3, 4};
}

I don't see what's so controversial about it. To me, it just looks like an alternate syntax for calling a constructor. On one hand, things could get ugly because you end up calling a function when all you think you're doing is initializing a few data feilds. On the other hand, I really enjoy how much verbosity it has the potential to eliminate. I'll probably use it sparingly.

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

Yeah...want to know how many times I was told I'd never use something when I was a beginner that I use often now? ;)

Well then, hopefully by the time he uses it, he'll have forgotten that I told him he'll never use it! :D

Tumlee 42 Junior Poster in Training

Never say never. ;) printf() supports a %n specifier that assigns the number of characters written up to that point:

Like I said, you will never use them (as in mattboy64). ;)

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

I reccommend nullptr's suggestion. You're going to have to get used to the double percent sign anyway, because there are some situations where you need to have both a format specifier and a percent sign in the same call to printf().

printf("Jimmy got a %d%% on his quiz!", percentage);
Tumlee 42 Junior Poster in Training

We would have to get a copy of what file you're working with to even begin to understand what your problem is.

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

Not possible. Line 27 is wrong, as I explained in my last post. open() doesn't take a std::string as the first argument, it takes only char*.

Perhaps he's using some old or otherwise nonstandard compiler that's somehow automatically typecasting std::string to const char*?

Tumlee 42 Junior Poster in Training

What you're probably looking for this the pre/post build steps tab under your project's Build Options... menu, which will allow you to set certain scripts to be executed whenever you build your project. Go to Project > Build Options... and then go to the tab that says Pre/Post build steps.

Tumlee 42 Junior Poster in Training

because typeof() is for GCC

It must be for a really old version of GCC. I'm running GCC 4.7 and it's telling me that typeof() is undefined. Even if it did, I don't see how this code could possibly compile on any compiler. You're setting y equal to a parenthesized block of code.

Tumlee 42 Junior Poster in Training

When you're using macros like this, please pay attention to exactly what the code looks like when your macro is expanded. The code you have here is equivalent to writing the following:

#include <stdio.h>
#include <conio.h>
void main()
{
int i=5;
int j=for(typeof(i) i=2; i<=n; i++){f *= i};
printf("%d",j);
getch();
}

Obviously this code makes no sense. You can't set a variable equal to a for loop, because it's not a function and therefore doesn't return a value. Furthermore, the variable f doesn't even exist in this context. This sort of thing is simply too complex to do with a macro. What you'll want to do instead is make a function to perform the same task.

#include <stdio.h>

int fac(int parm)
{
    int total = 1;
    int mult;

    for(mult = 2; mult <= parm; mult++)
    {
        total *= mult;
    }

    return total;
}

int main(void)
{
    int i = 5;
    int j = fac(i);
    printf("%d", j);
    return 0;
}
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

That code uses old, nonstandard functions like kbhit() and gotoxy(), which are functions that you'll hardly ever see outside of ancient compilers like Turbo C++ for DOS. Your best bet for ever getting this to work is trying to find curses.h on Google, and I'm not even sure if that exists for modern versions of Windows, let alone OSX.

Tumlee 42 Junior Poster in Training

Unfortunately, it would have to be even more complicated that that. You have to be able to intelligently ignore // when it occurs in quotes, otherwise, you would end up cutting strings apart. Take the following code, for example:

#include <stdio.h>

int main(void)
{
    printf("I like to // eat apples.\n");
    return 0;
}

Without a check to make sure the double slashes aren't in quotes, you would end up with this after running your program:

#include <stdio.h>

int main(void)
{
    printf("I like to 
    return 0;
}

This would, of course, generate a compiler error.

Tumlee 42 Junior Poster in Training

Have you written any code at all? Show us what you have working.

Tumlee 42 Junior Poster in Training

We're not going to go through your entire program, line by line, and figure out what's wrong with it. Unless you tell us what problem you're having and where, there's no point in 'debugging' it.

Tumlee 42 Junior Poster in Training

Sevaral problems here:

1) You're using charChoice as an index for accessing your charArray[] array. The character 'c' is equal to 99, so you're always just overwriting the last element of your array.

2) You successfully save the character that the user types into charArray[charChoice], but then your for loops overwrites that value a hundred times with an exclamation mark character, and it also sets everything in intArray[] to 0. This is why it's not remembering what you've wrote.

3) You declare the variables characterOfChoice and quanitityOfChar, but you're never using them anywhere.

I think it would be in your best interest to comment your code, read what you've wrote and try to understand what your program is doing.

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

When you have two functions of the same name that take a different list of parameters, this is called overloading a function. When you do this sort of thing on a class constructor function, it is callled an overloaded constructor. Your default constructor is the class constructor that you define that has no parameter list, so it is therefore called by default when you create an instance of your class with no parameters.

Take this code, for a good example of what I'm talking about:

#include <iostream>

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

class myclass
{
    public:
        //Default constructor, empty parameter list.
        myclass()
        {
            cout << "Default constructor was called." << endl;
        }

        //Overloaded constructor, taking an integer as a parameter.
        myclass(int parameter)
        {
            cout << "myclass constructor called with paramater " << parameter << endl;
        }
};

int main()
{
    //This calls the default constructor since you're just creating the object and not
    //giving it any parameters.
    myclass myobj1;

    //This calls the overloaded constructor myclass::myclass(int) because you supplied
    //an integer in parenthesis after the object name.
    myclass myobj2(32);
    return 0;
}

Your job here is to find out a good use for this technique, and implement it into the program you're writing.

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

Because the different format specifiers tell printf() to interperet the value differently when displaying it. When you use %c, it tells the program to read ch as a single character, in this case printing out the character with the ASCII value of 23. When you use %d, it tells the program to display ch like it's an integer, and just print out the number 23 in decimal form.

The printf() function can't really tell the difference between a char and an int without these format specifiers, it just sees ones and zeros. A char, in most environments, is really just an 8-bit integer that is designed to store a printable character on the screen.

Tumlee 42 Junior Poster in Training

If you're wondering why nullptr made these suggestions, here's why. On line 14, you're calling getch() but you're not actually storing the value returned by it anywhere, so the program isn't doing anything with your input. Changing the line to again = getch(); fixes this problem.

The reason he's suggesting you change the type of again to be an int is because you're storing the return value of getch() in there, and that function returns an int.

Tumlee 42 Junior Poster in Training

A segmentation fault indicates that you've accessed memory you shouldn't have. You should check variables that are being used as array indexes for these sorts of problems. This is one of those cases where you should debug with printf() to find out where your problem is. Track the value of i to see what's happening to it as you go through the loop. If you do, I guarantee you will find some very revealing information!