deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I don't mind indeterminate values at all if I access an array with no initial value. I just don't want my program crashing because of some undefined behaviour that I don't understand.

Those two sentences are contradictory.

I don't understand traps by just looking at it either.

Imagine calling abort, but without the happy result for a user. ;) I wouldn't wish troubleshooting a trap representation on even the worst of my enemies.

I asked someone why it was undefined and they said to me that the OS only gives memory to a variable when it has a value otherwise nothing happens :S

Wow, that was a stupid answer. Whoever told you that is quite confused. You get memory, you just can't necessarily predict the contents of that memory.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why is accessing data in an uninitialised array undefined behaviour?

It really depends on where the array is defined. If it's a local array then it's undefined behavior just as accessing an uninitialized variable is undefined behavior. The contents of the array are indeterminate, which is the "official" reason for the undefined behavior.

The practical reason is that accessing random bits can trigger something like a trap representation and totally blow up your application simply by looking at a value.

Any ideas what I could do to keep the speed of uninitialising without breaking any rules?

I'd need more details on what you're using the array for. Restructuring the array so you only access it sequentially rather than randomly would be a good start, but that's not always appropriate for the problem.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is there a specific reason you used a struct for the weapon but a class for the adventurer?

If it were a class, Weapon would need getters and setters for each data member. At that point I didn't see any need, so just made them public by default as a structure. Adventurer on the other hand has other stuff going on (including stuff that I didn't include for brevity), so it makes more sense to lock down the data members.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm still not seeing the issue. It should be a straightforward traversal of your list (assuming it->def is a definition instance as I showed in your other thread):

printf("Input: ");

if (fgets(line, sizeof line, stdin) != NULL) {
    struct node *it;

    line[strcspn(line, "\n")] = '\0'; // Trim the newline, if any

    for (it = head; it->next != NULL; it = it->next) {
        if (strcmp(line, it->def.value) == 0) {
            printf("Found '%s' in the word '%s'\n", line, it->def.key);
        }
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

because it doesn't help research the word since i'm getting only one strin

Your example contradicts what you're saying. Each line in the dictionary is a single defintion (ie. one string). The search word is only one string. I'm guessing that you simply don't know how to incorporate the snippet I gave you into the framework you have, but it's difficult to help when all you do is say it doesn't work and ask the same question again.

Please post all of your code as it stands right now.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The first chunk below lines up the decimals, but my "$"'s are too far, the second one fixes that and then the decimals are all F'd.

Right. The modifiers apply to the next item. If you don't want the "$" to be the next item, move it to before the modifiers:

cout << "$ " << fixed << setprecision(2) << setw(8) << right << 22.0 << endl;
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How are the weapons stored? Are they always a string in display format? Because it would be easier to have a weapon class that separates these things and makes it easier to work with:

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include <vector>

using namespace std;

struct Weapon {
    string _name;
    int _damage;
    int _value;

    Weapon()
        : _name(""), _damage(0), _value(-1)
    {}

    Weapon(const string& name, int damage, int value)
        : _name(name), _damage(damage), _value(value)
    {}
};

map<string, Weapon> supported_weapons = {
    {"Fist", Weapon("Fist", 1, -1)},
    {"Masamune", Weapon("Masamune", 52, 750)}
};

class Adventurer {
    vector<Weapon> _weapon_inventory;
    Weapon _equipped_weapon;
    int _base_damage;
public:
    Adventurer(int base_damage = 1)
        : _base_damage(base_damage)
    {
        _weapon_inventory.push_back(supported_weapons["Fist"]);
        equip("Fist");
    }

    void add_weapon(Weapon weapon)
    {
        _weapon_inventory.push_back(weapon);
    }

    Weapon equipped_weapon() const
    {
        return _equipped_weapon;
    }

    bool equip(const string& name)
    {
        auto match = find_if(
            _weapon_inventory.begin(), 
            _weapon_inventory.end(), 
            [&name](const Weapon& weapon) { return weapon._name == name; });

        if (match != _weapon_inventory.end()) {
            _equipped_weapon = *match;
            return true;
        }
        else {
            return false; // Weapon not available
        }
    }

    int roll_damage() const
    {
        return 1 + rand() % (_base_damage + _equipped_weapon._damage);
    }
};

In your code you might do something like this:

cout << "Choose a weapon to equip: ";

if (getline(cin, name) && equip(name)) {
    cout << name << " equipped\n";
}
else {
    cout << "Could not equip selected weapon\n";
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How was my previous answer to this question insufficient?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Did you write the remove_substring function? My example won't compile without it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i wanna know about what they represent ?

There are a number of barcode symbologies that have different data restrictions. Here's a quick overview of some common ones:

  • Code 3 of 9: Alphanumeric data. These are 1D barcodes in that they only have a series of vertical bars to encode the value.
  • Code 128: Alphanumeric data. Essentially a replacement for 3 of 9 when more data is required in less space. Also supports a larger character set.
  • UPC/EAN/JAN: Numeric data only, these are typically used for consumer products and inventorying in retail.
  • PDF417: Any data. This is a stacked 2D format where the "bars" (boxes, actually) run both vertical and horizontal. The encoding is rather extensive, so PDF417 can hold quite a bit of data in a relatively small space. Also includes optional error correction.
  • DataMatrix: Any data. Like PDF417 this is a 2D symbology with optional error correction. A benefit of DataMatrix is that it can encode data into a smaller barcoder than PDF417.
  • QR: Any data. Like most common 2D symbologies, a large amount of data can be stored in a relatively small space with optional error correction. The biggest benefits of QR are quick recognition and high availability of recognition libraries.

how they are created(with which information) ?

It depends on the symbology. 1D barcodes could be as simple as placing check characters on the end of the value ("*12345*" for 3 of 9), or as complex as a thorough compaction, encryption, …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but my teacher said vectors allocate way too much memory and its bad to use so many of them in one program :(

Sounds like premature optimization to me. Vectors are quite efficient, they only hold just enough memory to contain and manage what you put in them. If you choose what you put in carefully, it takes effort to waste memory.

if i make the variable static, will i have to change anything else for it to work?

Not really. But you'll find that if you change the vector in one object, all others will change as well. That can be surprising and undesirable in a case like this, depending on your needs for this particular inventory.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Can you point out places where you want to split the sentence? That's where you start, and figure out how to do it programmatically. Conveniently enough, my example showed how to use strtok, which is C's standard tokenization function. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but my task was to do by using strtok() fn

I love it when bad teachers ask you to do something with an approach that's woefully unsuited to it. :rolleyes: strtok isn't designed to "find" things, and any solution that attempts to use it that way is stupid.

You encountered one such reason for that. strtok doesn't recognize adjacent delimiters as being unique. There's no way around this without eschewing strtok and using some other ad hoc or non-standard tokenization library.

If I haven't been clear, strtok is the wrong solution. You cannot solve this problem just with strtok, period.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

From what I understand set() creates a column that will hold something less than it's size, and << right or << left will justifiy it.

Correct. But note that with the modifiers, typically they only affect the next item in the chain, not all further items.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

can you explain to me definition parsed_data?
what is it?

Read the code from my first post.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why not just keep it simple?

int vowels = 0;
int other = 0;

for (int i = 0; myarray[i] != '\0'; i++) {
    switch (myarray[i]) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        ++vowels;
        break;
    default:
        ++other;
        break;
    }
}

cout << "Vowels: " << vowels << '\n' 
     << "Other: " << other << '\n';
Assembly Guy commented: Kudos +5
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why would every different shop have the same inventory? ;) But to answer your question, look into making the vector a static member of the base class. Then it will be shared across the board.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The strcmp() function compares the ASCII values of the characters one by one

It compares the numeric values of the characters. It's not safe to assume that the character set is ASCII. Granted, ASCII and Unicode (where ASCII is a subset) are pervasive, but but not universal.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It compares each character in turn. If they have the same numeric value, it moves to the next character. When a mismatch is found, it returns the difference of the two numeric values[1].

Positive and negative are easy to see when looking at the values as being numeric:

1 - 2 = negative
2 - 1 = positive
1 - 1 = 0

[1] That's all that's required by an implementation. Some implementations, like mine above, will enforce strict -1, 0, or +1 as the return value.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The two headers are completely different. cstring is inherited from C and provides functions for working with C-style strings (arrays of char terminated by '\0'). string was born in C++ and defines the std::string class along with its non-member functions.

strcmp works like this:

int strcmp(const char *a, const char *b)
{
    while (*a == *b) {
        if (*a == '\0') {
            return 0;
        }

        ++a;
        ++b;
    }

    return *a < *b ? -1 : +1;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

|| has lower precedence than &&. To get the appropriate behavior (granted I'm assuming what behavior you want), you need parentheses:

(gps == 'Y' || gps == 'y') && (childseat == 'N' || childseat == 'n')
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Once again, this is just me, but I'd merge the two like this:

struct node
{
    definition parsed_data;
    struct node *previous;  // Points to the previous node
    struct node *next;   // Points out to the next node
}*head, *last;

Or like this, if you want to retain the original string:

struct node
{
    char data[100];
    definition parsed_data;
    struct node *previous;  // Points to the previous node
    struct node *next;   // Points out to the next node
}*head, *last;
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Deleting and modifying a file's contents in-place can be tricky. The general recommended approach is to read the file, write to a temporary file with the appropriate changes, delete the original file, then rename the temporary. the benefit of this approach is that it's simple reading and conditional writing. For example, to delete all instances of "foo" from a file:

FILE *in = fopen("test.txt", "r");

if (in != NULL) {
    FILE *out = fopen("temp.txt", "w");

    while (fgets(line, sizeof line, in) != NULL) {
        remove_substring(line, "foo");
        fputs(line, out);
    }

    fclose(out);
    fclose(in);

    remove("test.txt");
    rename("temp.txt", "test.txt");
}

Writing remove_substring is an interesting exercise, so I'll refrain from doing that for you. :) If the substring you want to delete contains a newline then the logic can get a bit hairy, but I'm guessing that's not going to be a likely case here, so the above logic should suffice.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'd start by breaking down the line into something more manageable:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct definition {
    char *key;
    char *datestamp;
    char *value;
} definition;

definition parse_definition(const char *s)
{
    char *copy = _strdup(s); // Make a copy for strtok
    char *tok = strtok(copy, "#");
    definition result = {0};

    if (tok != NULL) {
        result.key = _strdup(tok);
    }
    else {
        result.key = _strdup("");
    }

    tok = strtok(NULL, "#");

    if (tok != NULL) {
        result.datestamp = _strdup(tok);
    }
    else {
        result.datestamp = _strdup("");
    }

    tok = strtok(NULL, "#");

    if (tok != NULL) {
        result.value = _strdup(tok);
    }
    else {
        result.value = _strdup("");
    }

    free(copy); // Clean up temporaries

    return result;
}

int main(void)
{
    definition def = parse_definition("love_#2004#LOVING");

    printf("%s\n%s\n%s\n", def.key, def.datestamp, def.value);

    free(def.key);
    free(def.datestamp);
    free(def.value);

    return 0;
}

From there you can easily traverse the list of definitions and use strstr on value, then print key when there's a match.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It comes on a DVD. Just make sure that your BIOS is set to boot from CD/DVD and restart with the DVD in the drive.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

On re-read I'm guessing you perhaps thought this was outside the scope of the snippet?

Good guess. The code was taken almost verbatim from one of my services, but I had to cut out a few significant yet not entirely relevant pieces such as licensing, configuration settings, and company-specific names. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please post the actual string you're trying to parse.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just with strtok would be problematic. However, you can use strtok to split the string on & like this:

A1.1*7.1
9.1
11.1/

Then manually parse each token to get the ranges. For example:

char s[] = "A1.1*7.1&9.1&11.1/";
char *tok = strtok(s, "&");

while (tok != NULL) {
    char *sep = strchr(tok, '*');

    if (sep != NULL) {
        // Found a range
        printf("%.*s - %s\n", sep - tok, tok, sep + 1);
    }
    else {
        // No range
        printf("%s\n", tok);
    }

    tok = strtok(NULL, "&");
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Consider a simple linked list insertion sort. Instead of a direct comparison with relational operators, look at using strcmp on the data member instead and you'll be good to go.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hello, this would be my second time in posting a question which I solved by myself.

Well done. Being able to solve your problems yourself is a great ability to cultivate. Unfortunately, a lot of people will ask a question and then stop working on it in the hope that someone else will answer it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Go to your control panel, then enter Control Panel\Appearance and Personalization\Display into the address bar. Make sure the scaling level is set to 100%. When I upgraded to 8.1, it had it defaulted to 125% and your issue sounds like the one I was having.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Also note that your thread titles are very uninformative.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In my job I tend to write a lot of Windows services. Due to this I've pared it down to bare essentials so that the code is as simple as possible, but still fully functional for the needs of each service. What this generally means is I don't use the service project in Visual Studio, instead favoring template code. After learning how services work, I found that the project was unnecessarily complex.

Barring an installer, the basic project would have only two files:

  • Program.cs: Setup and startup
  • Service.cs: The actual service

I usually separate the service from a service worker that does actual work, but that's application specific.

Program.cs sets up logging, any custom application settings, and runs the service normally. However, over the years I've found that a debug mode for my services is invaluable in both development and after deployment. If the executable is run interactively, it runs in a console and displays logging there as well. Here's a sample template for Program.cs:

public class Program
{
    /// <summary>
    /// Gets or sets the application's data folder.
    /// </summary>
    public static string ApplicationFolder { get; set; }

    /// <summary>
    /// Gets or sets the location of the file log.
    /// </summary>
    public static string LogFolder { get; set; }

    /// <summary>
    /// Gets or sets the log manager for the application.
    /// </summary>
    public static LogManager Log { get; private set; }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    public static …
Ketsuekiame commented: Good service foundation template +11
ddanbe commented: Nice! +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

/^[[:alnum:]]*$/

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm not sure if ODBC works for Word, it would surprise me, to be honest.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But it must work if the Ms word is not present

That's what makes things difficult. If the Office API isn't available, you have no choice but to work around it somehow. I've done this when reading Excel files (ODBC works nicely), but not with Word.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm not sure, that's why I suggested research. ;) A quick search shows potential options, but I can't offer a recommendation without more extensive poking around.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Classic. Your link is broken though. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

C++11 (3.6.1 Main Function)

"A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. [Note: In a freestanding environment, start-up and termination is implementation-defined; startup contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration. —end note ]"

In other words, all bets are off in a freestanding environment. main can be required or not, and by extension, the signature defined for hosted environments is not required either.

Through a loophole in the wording, the C standard (up to and including C11) allows void main in a hosted environment provided int main is also supported. There too, all bets are off for freestanding environments. I'm not sure about C14 though, I haven't been keeping up with the bleeding edge of standardization.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

it's int main(), never void main() because main() always returns an integer back to the operating system.

Except when the program is freestanding and not hosted by an operating system. But if you're writing a freestanding program, you're probably not asking for help on a place like Daniweb. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

which would mean stable_sort would arrange those string with the same length in alphabetical order, is it?

No, stable_sort would retain the original order of those strings with the same length.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I can play that game too.

We won't do your homework for you. What have you tried?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

We won't do your homework for you. What have you tried?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Let's start by getting a clear idea of what the question is asking. What does "stream" mean in that context? C++ already has a definition for "stream", and it doesn't mesh well with how it's used in your assignment.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

My usual answer to "I don't know how to start" is, did you pay attention in class? If you didn't, it's tough love, but I'd say that you deserve to fail and should learn the lesson: Nobody will bail you out. It's a lesson that should be learned early, because it's a hard lesson, and it's reality.

I want to help you, I really do. But at this point the only way to do that is to do at least a large part of your homework for you. And from that you learn nothing.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Post the code you've tried and how it didn't work. We can explain why it doesn't work and offer suggestions for how to fix it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I can't help you until you ask a real question. Just posting your homework assignment is against Daniweb rules.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

"Help" does not mean "do it for me". Post your code, ask a real question, and stop appearing as if you're trying to cheat on your homework.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

A form is not a process. You can wrap it in a process, after a fashion, but that would sever any connection with the calling form and process.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Have you tried anything at all yet? This is a straightforward loop.