Thanks, that clears up a lot.

One follow-up:
(unsigned long*)host->h_addr
and
(SOCKADDR*)(&socket_address)
are doing the same thing, recasting as pointers as I see it. Does this mean host->h_addr is a reference or can anything be recast as a pointer, say an int or a pointer to a pointer to a char, a pointer to a pointer to a pointer to an array?

ETA: I guess my question is: what sort of things could host->h_addr possibly be aside from a reference?

ETA2: The application looks like this in regards to the host pointer:

    struct hostent *host;
    if ((host = gethostbyname("localhost")) == NULL)

Should there be an
malloc(sizeof(hostent))
between those two lines?

Following a tutorial, I built a small sample program that uses winsock. It compiles, but there are a few different places I'm not sure what's happening with the pointers. Full source is available here

Line 25:
struct hostent *host;

As near as I can tell, this creates a pointer to a memory address holding an instance of the "hostent" struct and refers to it as "host." What I can't figure out is why
hostent *host;
or

hostent h;
host = *h;

wouldn't accomplish the same thing, as hostent is already an existing struct in the winsock2 header.

Line 37:
socket_address.sin_addr.s_addr = *((unsigned long*)host->h_addr);

The right side, I find utterly baffling. For the "*" inside the parenthesis and to the right of "unsigned long" I can't figure out the significance. As for the one directly to the left of the parentheses, does this just mean the right side provides a pointer to a memory address holding an unsigned long int?

Line 40:
if(connect(server_socket,(SOCKADDR*)(&socket_address), sizeof(socket_address)) != 0)

The second argument the connect function expects is, according to msn's documentation, "[a] pointer to the sockaddr structure to which the connection should be established." As such, it stands to reason that the second argument provided here takes the "SOCKADDR_IN" instance "socket_address" and provides a pointer to it. What I can't understand is the reasoning behind why this syntax does that, and even trying to explain what little I thought I had figured out confused me to the point that whatever logical progress I thought ...

I'm trying to do something simple like get calc.exe to start minimized, but it's not happening.

import subprocess
import win32gui
import win32con

info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = win32con.SW_SHOWMINIMIZED
x = subprocess.Popen("calc.exe", startupinfo = info)

It pops up the same as always, no matter what I provide for wShowWindow.

I've got an application that I call several times in a for loop using subprocess.call. Every time I call it, it starts minimized. I want it to be in a restored window. So what I've tried to do is get a handle on the window using win32gui.FindWindow. But in my current setup, FindWindow doesn't run until after the process is finished.

from subprocess import call
from os import getcwd
from win32gui import FindWindow
from win32gui import ShowWindow

settings_files = list([file_1, file_2, file_3])
#this creates a command "%executable_path%\spider_3.0.exe /run"
spider_app = "\"%s\" /run % ("join(getcwd(), "spider_3.0.exe"))

while len(settings_files) != 0:
    current_settings_file = settings_files.pop()
    import_settings(current_settings_file)
    call(spider_app)
    spider_window = FindWindow(None, "Spider 3.0.0")
    ShowWindow(spider_window, 9)

This obviously waits until the application has finished running before trying to get the window handle so it doesn't work. Detaching the process doesn't work either, as I need to wait for the process to finish, otherwise, I'll end up launching several instances of the application at once when I only want one to run at a time, the script will continue, and it will fail when it gets farther down and tries to use the output from the application.

And the final script, since I figure it will be useful to someone.

from _winreg import *

def find_subkeys(key, subkeys, scanned_subkeys):
    current_key = OpenKey(HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS)
    for i in range(4096):
        try:
            subkey = EnumKey(current_key, i)
        except:
            subkey = None
        if subkey:
            subkey = r"%s\%s" % (key, subkey)
            if not subkey in subkeys and not subkey in scanned_subkeys:
                subkeys.append(subkey)
    scanned_subkeys.append(key)
    CloseKey(current_key)

def delete_values(key):
    current_key = OpenKey(HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS)
    values = list()
    for i in range(4096):
        try:
            value = EnumValue(current_key, i)
        except:
            value = None
        if value:
            values.append(value[0])
    for i in values:
        DeleteValue(current_key, i)
    CloseKey(current_key)

def delete_key(key):
    key = key.rstrip("\\")
    subkey = str()
    for letter in key[::-1]:
        if letter != "\\":
            subkey += letter
        else:
            break
    subkey = subkey[::-1]
    key = key[:(len(key) - len(subkey) - 1):1]
    current_key = OpenKey(HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS)
    DeleteKey(current_key, subkey)
    CloseKey(current_key)

def main():
    subkeys = list(["Software\CUSpider\Spider3"])
    scanned_subkeys = list()
    while len(subkeys) != 0:
        find_subkeys(subkeys.pop(), subkeys, scanned_subkeys)
    scanned_subkeys.sort(lambda x,y: cmp(len(x), len(y)))
    while len(scanned_subkeys) != 0:
        current_key = scanned_subkeys.pop()
        delete_values(current_key)
        subkeys.append(current_key)
    subkeys.reverse()
    while len(subkeys) != 0:
        current_key = subkeys.pop()
        delete_key(current_key)

if __name__ == "__main__":
    main()

Managed to fix the second issue by adding the items to a list and iterating that list to delete. And it's just occurred to me that that's because I was modifying the quantity and positions of the values as I was trying to enumerate them. I'm an idiot.

from _winreg import *

def find_subkeys(key, subkeys, scanned_subkeys):
    current_key = OpenKey(HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS)
    for i in range(4096):
        try:
            subkey = EnumKey(current_key, i)
        except:
            subkey = None
        if subkey:
            subkey = r"%s\%s" % (key, subkey)
            if not subkey in subkeys and not subkey in scanned_subkeys:
                subkeys.append(subkey)
    scanned_subkeys.append(key)
    CloseKey(current_key)

def delete_values(key):
    current_key = OpenKey(HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS)
    values = list()
    for i in range(4096):
        try:
            value = EnumValue(current_key, i)
        except:
            value = None
        if value:
            values.append(value[0])
    for i in values:
        DeleteValue(current_key, i)
    CloseKey(current_key)

def main():
    subkeys = list(["Software\CUSpider\Spider3"])
    scanned_subkeys = list()
    while len(subkeys) != 0:
        find_subkeys(subkeys.pop(), subkeys, scanned_subkeys)
    scanned_subkeys.sort(lambda x,y: cmp(len(x), len(y)))
    while len(scanned_subkeys) != 0:
        delete_values(scanned_subkeys.pop())

if __name__ == "__main__":
    main()

Fixed it myself, partially.

Delete(current_key, value[0])

Now it seemingly leaves random values lingering, though, and I have to run it several times to actually clear the thing out.

I've been strugglin with this all day. I'm trying to use python to walk through a registry key and delete all the values it finds. I've succeeded in getting it to find all the nested values, but as soon as I try to delete one, I'm met with "WindowsError: [Error 2] The system cannot find the file specified."

I'm sure it's something simple I'm doing wrong, but I can't for the life of me figure out what it is.

from _winreg import *

def find_subkeys(key, subkeys, scanned_subkeys):
    current_key = OpenKey(HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS)
    for i in range(4096):
        try:
            subkey = EnumKey(current_key, i)
        except:
            subkey = None
        if subkey:
            subkey = r"%s\%s" % (key, subkey)
            if not subkey in subkeys and not subkey in scanned_subkeys:
                subkeys.append(subkey)
    scanned_subkeys.append(key)
    CloseKey(current_key)

def delete_values(key):
    current_key = OpenKey(HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS)
    for i in range(4096):
        try:
            value = EnumValue(current_key, i)
        except:
            value = None
        if value:
            value_to_delete = r"%s\%s" % (key, value[0])
            print value_to_delete
            DeleteValue(HKEY_CURRENT_USER, value_to_delete)
    CloseKey(current_key)

def main():
    subkeys = list(["Software\CUSpider\Spider3"])
    scanned_subkeys = list()
    while len(subkeys) != 0:
        find_subkeys(subkeys.pop(), subkeys, scanned_subkeys)
    scanned_subkeys.sort(lambda x,y: cmp(len(x), len(y)))
    while len(scanned_subkeys) != 0:
        delete_values(scanned_subkeys.pop())

if __name__ == "__main__":
    main()

Disregard that. I see now that with the way I've got it set up now, I've given myself an opportunity to delete the pointer more than once, resulting in runtime errors.

Loud and clear and explained well enough that a five-year-old could understand it. I guess my next question in this line (and I think I have a good idea what the answer is) would be:

Is it considered good practice to allocate memory on the heap if I want to be able to deallocate it before the object goes out of scope, or is it better to redesign my scope altogether so that the object is contained only so long as it is needed, returning necessary values? This is what I'm looking at right now:

/*The Configuration class has a self-contained menu subroutine for editing the application settings that is called from the main menu. The Configuration instance is allocated on the heap and its constructor initializes the settings. Once an option is chosen on the main menu doesn't involve creation/modification of settings managed by the Configuration class, relevant data is pulled from the Configuration instance, and it's then deleted before moving on.*/
void home_menu()
{
    Configuration *cfg = new Configuration;

    string main_opt;
    bool exit_home = false;
    do
    {
        cout << "[S]can, [O]ptions, E[x]it" << endl;
        getline(cin, main_opt);
        if (main_opt.size() == 1)
        {
            transform(main_opt.begin(), main_opt.end(), main_opt.begin(), ::tolower);
            if (main_opt.compare("o") == 0)
                cfg->options_menu();
            else
            {
                params_struct params = cfg->get_params();
                delete cfg;
                const params_struct &rParams = params;
                if (main_opt.compare("x") == 0)
                    exit_home = true;
                else if (main_opt.compare("s") == 0)
                    cout << "Let's scan!";
                else
                    cout << "Invalid selection." << endl;
            }
        }
        else
            cout << "Invalid selection.";
    } while (exit_home == false); ...

I believe I understand now. Also, nice catch on the missing brackets. Much obliged.

Someone looking at my code today told me that I didn't need to delete a pointer I declared in one place because I didn't create it using the "new" operator and went on to say that you only have to delete them when you use the "new" operator to declare them. Is this accurate? Relevant code included, the pointer is to a vector object within a struct named "pParams".

/*use parameter name to determine which member of the
pParam struct should be affected*/
void Cfg::proc_param(string name, string value)
{
    vector<string> *param_vector;

    bool bad_param_name = false;
    if (name == "dirs_recursive")
        param_vector = &pParams.dirs_recursive;
    else if (name == "dirs_nonrecursive")
        param_vector = &pParams.dirs_nonrecursive;
    else if (name == "files")
        param_vector = &pParams.files;
    else
        cout << "Invalid configuration paramter " << name << endl;
        bad_param_name = true;

    delete param_vector;
}

You also have to decide how much you care.

If I didn't care, I'd have stuck to python,

If these are short strings, this is a fast function regardless.

More than a handful over 256 characters, more than a few over 1024. Granted, it's largely academic at this point in time, but I fully intend to produce FOSS code for a niche that is sorely lacking in FOSS code.

See my post again. SINGLE, not double quotes. You're comparing a character to a character. Nothing to do with Linux or mingw. What you had would "barf" no matter what compiler.

Dammit, sorry. Not the first time I've run across this. Python spoiled me in this regard.

See also the earlier point(partially) regarding lines 28 and 29. No need for the "if", then assigning it to true if it was false. Just assign it to true.

With you. Thanks a lot.

if (line[ss] == "=") == 0)

Mingw definitely barfs here with "ISO C++ forbids comparison between pointer and integer"

update:
Here's what I'm looking at now; it's compiling, running and doing what it's supposed to.

void proc_cnf_line(Settings& settings, const string line)
{
    string param_name;
    string param_value;
    bool param_named = false; //for deciding which string characters are placed into as encountered
    bool param_val_encountered = false; //for getting rid of leading spaces in param values
    const strsize line_size = line.size();
    for (strsize ss = 0; ss < line_size; ss++)
    {
        if (param_named == false)
            {
                if (line.compare(ss, 1, "=") == 0)
                    param_named = true;
                else
                {
                    if (line.compare(ss, 1, " ") != 0)
                        param_name += line[ss];
                }
            }
        else
        {
            if (param_val_encountered == true)
                param_value += line[ss];
            else
            {
                if (line.compare(ss, 1, " ") != 0)
                {
                    if (param_val_encountered == false)
                        param_val_encountered = true;
                    param_value += line[ss];
                }
            }
        }

    }
}

I can't do a simple comparison of

if (line[ss] == "=")

since one of them results in an integer (I forget which, but recall running into either "H" or "K" repeatedly spitting out "104" when I was previously trying to run tolower() through cout) and the other a pointer. I'm thinking I might benefit from a character type primer, and I will look for one, but I'd be grateful to anyone who could takiea few paragraphs to spell out the ABCs for me until I find it. I know there is a more efficient way of doing this.

As to your code itself, looks like you're splitting the string into two strings using = as the delimiter and tossing the spaces.

It is possible that a "=" could be held within the second string, though, since it will sometimes contain file paths and I'm going for 'nix compatability.

You're right though:

if (param_value_encountered == true)
    param_value += line[ss]
else
{
    if (line.compare(ss, 1, " ") != 0)
    {
        if (param_val_encountered == false)
            param_val_encountered = true;
        param_value += line[ss];
    }
}

is what I'm going for. In retrospect, though, getting rid of leading spaces would also be counterproductive in terms of 'nix comaptability without a separate subroutine to see if the leading spaces were intentional or not.

if(line[ss] == '=') // or any of the other comparisons

I was not actually aware that I could do this. I knew it worked in python, but for whatever odd reason, I seem to recall it failing spectacularly in mingw.

There's some quick math to get an address. I wouldn't worry about it much.

Any real reason not to though?

edit:

if (line[ss] == "=") == 0)

Mingw definitely barfs here with "ISO C++ forbids comparison between pointer and integer"

I just can't help but feel that there's a more efficient way to do this than with multiple calls to the string[i] operator.

I've tried storing the results of string[i], but that leaves me with a char, which I'm evidently unable to compare. I know that I can compare a char*, but from what I can tell, that's a C char and string[i] provides me with a C++ char.

I could be way off with my entire analysis of the situation, so any help would be greatly appreciated.

void proc_cnf_line(Settings& settings, string line)
{
    string param_name;
    string param_value;
    bool param_named = false; //for deciding which string characters are placed into as encountered
    bool param_val_encountered = false; //for getting rid of leading spaces in param values
    for (strsize ss = 0; ss < line.size(); ss++)
    {
        if (param_named == false)
            {
                if (line.compare(ss, 1, "=") == 0)
                    param_named = true;
                else
                {
                    if (line.compare(ss, 1, " ") != 0)
                        param_name += line[ss];
                }
            }
        else
        {
            if (line.compare(ss, 1, " ") != 0)
            {
                if param_val_encountered == false
                    param_val_encountered = true;
                param_value += line[ss];
            }

        }

    }
}

Thanks. Are they interchangeable?

I'm sure I'm missing something basic here, but I cannot get this to compile. Using codeblocks 10.05 with mingw build of gcc 4.4.1. I've included unistd.h and tried replacing MAXPATHLEN with PATH_MAX but every time, it gives me:

error: 'MAXPATHLEN' was not declared in this scope

or

error: 'PATH_MAX' was not declared in this scope

#include <iostream>
#include <unistd.h>

int main()
{
    char temp[MAXPATHLEN];
    return 0;
}

I've also tried

#include "unistd.h"

to no avail.

I stand corrected. Apparently, Code::Blocks does that on exception. If I just build the binary and run it from outside of Code::Blocks, it does exactly what's expected of it. False alarm, my fault.

[QUOTE=Chilton;1650542]In your catch statement, you referred to e but you never used it. Instead of [CODE]cout << "exception handled" << endl;[/CODE] try [CODE]cout << e.what() << endl;[/CODE]
That should display the error string that you threw. If you want to specify it as an error, you could use cerr instead of cout as well.[/QUOTE]

I know I currently have an unused variable. This is a small sample to illustrate the problem I'm having.
[CODE]cout << e.what() << endl;[/CODE]
suffers from the same problem, as does
[CODE]cerr << e.what() << endl;[/CODE]

The unused variable is not the issue here. The issue is that the code in my catch block isn't getting executed unless I make it continue in the step-through editor.

I've made a simple function that takes a vector as an argument. If the vector is empty, it throws a domain_error (I've included stdexcept).

I'm feeding it an empty vector from the main loop just to learn try...catch statements and when it catches the error, it's supposed to print something and carry on. Instead, however, it hangs on catching the error. I know I'm close, though, because if I use the step-through debugger in code::blocks and tell it to go to the next line, it continues as I'd expect it to. Why won't the executable do this on its own?

Sorry if this has been asked before, my search didn't come up with anything, and thanks in advance.

[CODE]

include
include
include
include
include
include

using namespace std;

double get_median(vector vec)
{
if (vec.size() == 0)
throw domain_error("Can't find median of empty vector");
return 5.5;
}

int main()
{
vector vec;
try
{
double med = get_median(vec);
}
catch (domain_error& e)
{
cout << "exception handled" << endl;
}
system("pause");
return 0;
}
[/CODE]

[QUOTE=firstPerson;1643084]>>[B] cin >> a >> b >> read_hw(cin, homework);[/B]

that essentially turns into [icode] cin >> cin [/icode] which doesn't make sense. I agree, for your function, read_hw you should make it void. Enabling syntax such as [icode]read_hw(cin,homework) >> a >> b [/icode] is obfuscated.

Just think read_hw as a regular function and call it as a regular function in its own statement. Don't try to use the returned value as there is no need. A better approach would be this :
code
[/QUOTE]

Thanks a lot. Guess I'll have to read more to figure out why he did it the way he did.

disclaimer: this is going to be really noobish.
so i put together this:
[CODE]

include
include
include
include

using namespace std;

istream& read_hw(istream& in, vector& hw)
{
if (in)
{
// get rid of previous contents
hw.clear();
// read homework grade
double x;
while (in >> x)
hw.push_back(x);
// clear the stream so that input will work for the next student
in.clear();
}
return in;
}

int main()
{
double a, b;
vector homework;
cin >> a >> b >> read_hw(cin, homework);
system("pause"); //bad form, i know
return 0;
}
[/CODE]

and the error i get is:
ambiguous load for 'operator>>' etc.
thoughts? i'm clearly failing to grasp something very basic here.

I'm working my way through Accelerated C++ and I've come across this exercise. The read_hw function works fine if it's void as long as I comment out the "return in" line. The author didn't bother to explain why he's returning a reference to the cin that was passed in the first place. Also I'm not sure what to make of the if (in) here, since it was passed as a parameter it seems like it should be there. I would greatly appreciate any (correct) explanation for almost anything going on here related to istream/cin.

[code]
// read homework grades from an input stream into a vector
istream& read_hw(istream& in, vector& hw)
{
if (in)
{
// get rid of previous contents
hw.clear();
// read homework grade
double x;
while (in >> x)
hw.push_back(x);
// clear the stream so that input will work for the next student
in.clear();
}
return in;
}

int main()
{
vector homework;
read_hw(cin, homework);
return 0;
}

[/code]

I'm used to c++ along with an open database (switched from mysql to postgres not too awful long ago.) A new job I'm looking at taking focuses heavily on .net along with SQL Server. As such, I've been looking into the .net framework and what I can't seem to figure out is how to make sure I'm actually using it. From what I've gathered, C# and VB.net are both managed languages, and someone mentioned that there is a managed C++ that compiles first to Microsoft CLR.

Is using Visual C++ enough to ensure I use this "Managed C++." Does this mean I don't have to worry about destructors? Would using destructors have any effect at all? Seems it would make for more efficient code to destroy pointers and just keep the gc as a second set of eyes watching for memory leaks. My experience with managed code is pretty much nil.

Thanks in advance.

[QUOTE=westony;1639744]I don't want anyone to do my code. Just to give me the idea and I will code it my self.

I just can not understand how to plant them yes this time i need a little example how would look like the code but not the entire code...

How it will look like the code for one Turret to put it on coordinates x=10 y=20 ?[/QUOTE]

[CODE]
class Turrent {
private int _x_coordinate;
private int _y_coordinate;

 public void Turret(int x, int y)
 {
      _x_coordinate = x;
      _y_coordinate = y;
 }
 public int get_x() { return _x_coordinate; }
 public int get_y() { return _y_coordinate; }

}
[/CODE]

Your map class will create the turret object with coordinates x and y when the turret is placed. The map class will position the turrets on itself based on the return values of get_x() and get_y() (although really it should do that without having to call those member functions when the turret is placed.) Now it just looks like you need to create the map!

[QUOTE=Momerath;1639733]C# and VB.NET are managed languages (and there is a version of managed C++)[/QUOTE]

Is using Visual C++ enough to ensure I use this "Managed C++." Does this mean I don't have to worry about destructors? Would using destructors have any effect at all? Seems it would make for more efficient code to destroy pointers and just keep the gc as a second set of eyes watching for memory leaks. My experience with managed code is pretty much nil.

Mouse's x,y coordinates on the canvas. If it's a grid, then it's that much easier. Have you coded anything for this yet? Your question is very vague and it seems like you want someone to code the entire system for you. Can we see the code you have for the map so far? Can you simplify the problem? i.e.: something along the lines of "Here is a map I created and here is a doohickey that I created to place on it. How can I use my mouse to plant the doohickey where I want it?"

edit: Also, I'm not sure you're using the right tools for the job. Not sure where php would come into play, since, IIRC, it needs a page refresh to change the content. Unless the tower defense game is turn-based, you're going to need to look more toward HTML5 or (shudder) flash. Why are you using SQL queries?

X, Y coordinates?