Gonbe 32 Newbie Poster

I'm not familiar with Rail Fence cypher but at a first glance your code is full of odd things. Without knowing what rail fence cypher is or how it works I think I do understand what you are trying to do and I tried to correct it. Added some comments as remarks.

#include <iostream>
#include <cstring>
#include <cmath>

using namespace std;

const int GRID_ROWS     = 3;
const int GRID_COLUMNS  = 80;

// Global variables make bunnies cry. Pass it between functions instead.
char GRID[GRID_ROWS][GRID_COLUMNS];

// Wouldn't do function names in caps, but that's a style thing I guess..
int  MENU(int menu_choice);
void REVIEW_OF_GRIDS_FIRST_79_CHARACTERS();

int main()
{
    // High "This is sparta!" factor. But again a style thing. =)
    cout << "                         This is RAIL FENCE CIPHER\n" << endl;

//-----------------------------------------------------------------------------------------------------
//filing GRID with asterisks(*)

    // Changed it to make it easier to read and maintain.
    for (int k = 0; k < GRID_ROWS; k++)
    {
        for (int i = 0; i < GRID_COLUMNS; i++)
        {
            GRID[k][i] = '*';
        }
    }

//-----------------------------------------------------------------------------------------------------
//plaintext input into GRID

    // Why size 0? Use a string instead.
    // char plaintext[0];
    string plaintext;

    // Might want to use getline. (not sure what your requirements are)
    cout << "Enter message to encode:" << "                 NOTE:Asterisk(*) symbol is not allowed\n";
    cin >> plaintext;


    // If 99 is irrelvant, why include it? I removed it.
    int grid_row[] = {0,1,2,1};
    const unsigned int PATTERN_SIZE = sizeof(grid_row) / sizeof(int);

    // grid_position_X is equal to plaintext_counter? I removed it.
    // Also, …
Gonbe 32 Newbie Poster

This is incorrect:

pina = (int **) malloc (sizeof(int *) *c);
    pinb = (int **) malloc (c* sizeof(int *));
    pinc = (int **) malloc (c* sizeof(int *));

'c' is 'm' times 'n' so you're dynamically allocating an array of m*n pointers to integers. You're never allocating the things these should point to though. You can do something like this, but then you'll want to use a 1-dimensional array to store a 2-dimensional array.

So you have to change that to:

// Allocate the pointers to arrays
    pina = (int **) malloc (m * sizeof(int *));
    pinb = (int **) malloc (m * sizeof(int *));
    pinc = (int **) malloc (m * sizeof(int *));

And then add the following after it:

// Allocate the arrays.
    for (i = 0; i < m; i++)
    {
        pina[i] = (int*) malloc (n * sizeof(int));
        pinb[i] = (int*) malloc (n * sizeof(int));
        pinc[i] = (int*) malloc (n * sizeof(int));
    }

That's the direct cause of your problem, but you should remove this from the start:

free(pina);
    free(pinb);
    free(pinc);

and also this

for (i=0;i<m;i++)
        {
        for (j=0;j<n;j++)
            {
            pina[i][j]= NULL;
            pinb[i][j]= NULL;
            pinc[i][j]= NULL;
            }
        }

And freeing is changed to from this:

free(pina);
    free(pinb);
    free(pinc);

to this:

// Free the arrays.
    for (i = 0; i < m; i++)
    {
        free(pina[i]);
        free(pinb[i]);
        free(pinc[i]);
    }

    // Free the pointer to arrays.
    free(pina);
    free(pinb);
    free(pinc);
Gonbe 32 Newbie Poster

Your code is difficult to read due to the poor naming of variables and the complete lack of comments. Aside from that it just doesn't make much sense. Trying to make sense of it I added some comments:

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

int main(void)
{
    int a = 0;  // Will be sum(i).
    int d = 0;  // You probably try to let this contain the amount of divisors.
    int j;      // For-loop variable.
    int i;      // For-loop variable.
    int dig;    // Will contain how many times a 'j' fits into 'a'.

    // Warning: "i == i" will result in an endless loop. Is this what you want?
    for (i = 0; i == i; i++)
    {
        // 'a' will be sum(i).
        a = a + i;

        // Go past every number smaller than sum(i), starting at 1.
        // You might want to change '<' to '<=' or let j start at 0.
        for (j = 1; j < a; j++)
        {
            // dig will contain the amount of times 'j' fits into 'a'.
            // This might not be what you want it to do, going by your next statement.
            dig = a / j;

            // 'isdigit' wants a char and you're providing it with ASCII values now. If 'a' isn't divisible by 'j' dig will contain the highest multitude of
            // j smaller than a. (e.g. 5/2 = 2) Search for "integer division" for more information. If you want
            // to check for divisibility you could …
Gonbe 32 Newbie Poster

Hi.

I'm a wise daniweb member and as such I'd like to inform you that we do not do your homework here as stated in the rules. Ofcourse this has been mentioned by 3 other people in this thread already making this completely redundant but my calling as an enforcer of the law is simply too strong even though there's already too many of us. This doesn't stop me however as it's proven to be an easy way to get upvotes, mainly from my fellow law enforcers. In addition I also like to think it makes me come across as an established and seasoned member. One could argue that reputation points are useless as it doesn't really unlock any benefits but in my opinion it adds a lot actually because the more I have, the more humble people will become in my presence; or atleast I like to think so!

xoxo,

Gonbe.

Gonbe 32 Newbie Poster

A function prototype is also called a function declaration. You supplied a function definition. In addition you don't follow the description. You function returns nothing while the description mentions it has to return the largest of the two. The function prototype would be:

// Precondition:  <add>
// Postcondition: <add>
int max (const int a, const int b);

The 'const' keyword is optional but recommended to prevent unintented modification of either of the parameters by accident. The way you comment the function is up to you as well. Some use pre- and postconditions, others use doxygen-style comments while others simply have a short description.

Gonbe 32 Newbie Poster

If the double pointer thing confuses you too much you could also go for a different solution. For example, you could make the functions return the new version of a supplied list. Calls would then typically look something like:

list = DoSomethingWithList(list);

When applied to your code you get something like this:

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

// Includes the NULL character.
#define DATA_SIZE (20)

struct linked
{
    char data[DATA_SIZE];
    struct linked *next;
};

typedef struct linked node;

node* choice (node* list);
node* enter  (node* list);
node* addNode(node* list, const char data[]);

int main()
{
    node *list = NULL;
    node *listItem = NULL;
    int i;

    list = choice(list);

    // Little test. Just show all linked list contents.
    printf("Linked list contents:\n\n");

    for (listItem = list, i = 1; listItem != NULL; listItem = listItem->next, i++)
    {
        printf("%d. \"%s\"\n", i, listItem->data);
    }

    // Freeing etc here. Yes, I am lazy..

    return 0;
}


node* choice(node* list)
{
    int n;

    do
    {
        printf("Enter choice: ");
        fflush(stdout);

        scanf("%d",&n);

        switch(n)
        {
            case 1:
                list = enter(list);
                break;

            default:
                printf("Try again.\n");
        }
    }
    while(n != 1);

    return list;
}


node* enter(node* list)
{
    char entered[DATA_SIZE] = { '\0' };
    printf("Enter the data. Type END if finished.\n");

    scanf(" %[^\n]", entered);
    while (strcmp(entered,"END") != 0)
    {
       list = addNode(list, entered);
       scanf(" %[^\n]", entered);
    }

    return list;
}

node* addNode(node* list, const char data[])
{
    // The supplied list is empty. This means this is where our new node belongs.
    if (list == NULL)
    { …
Gonbe 32 Newbie Poster

What I am trying to say is that "list" would still be NULL after adding the node "hello" in the last example. It's because the pointer is passed by value and not by reference. You could see the "double pointer" as a reference of a pointer if that makes it easier.

A small example:

#include <stdio.h>

typedef int* IntPtr;

void ChangePointerByValue (IntPtr value)
{
    // Random value, just as a test.
    value = 0xCAFEBABE;
}

void ChangePointerByReference (IntPtr* value)
{
    (*value) = 0xCAFEBABE;
}

int main(void)
{
    IntPtr pointer = NULL;
    printf("Pointer is: %p.\n", pointer);

    ChangePointerByValue(pointer);
    printf("Pointer is: %p.\n", pointer);

    ChangePointerByReference(&pointer);
    printf("Pointer is: %p.\n", pointer);

    return 0;
}

This will result in something like:

Pointer is: 00000000.
Pointer is: 00000000.
Pointer is: CAFEBABE.

The pointer to a pointer is basically the same without a typedef. So I could have written the above like this:

#include <stdio.h>

void ChangePointerByValue (int* value)
{
    // Random value, just as a test.
    value = 0xCAFEBABE;
}

void ChangePointerByReference (int** value)
{
    (*value) = 0xCAFEBABE;
}

int main(void)
{
    int* pointer = NULL;
    printf("Pointer is: %p.\n", pointer);

    ChangePointerByValue(pointer);
    printf("Pointer is: %p.\n", pointer);

    ChangePointerByReference(&pointer);
    printf("Pointer is: %p.\n", pointer);

    return 0;
}

When you pass a parameter by value it's value is copied and changes made to the function parameter within the function will remain local; they do not modify the parameter supplied to the function. A call by reference (although not really a reference, it's a pointer but the term …

Gonbe 32 Newbie Poster

Something like this?

#include <stdio.h>
#include <assert.h>

void DrawSpiralLine(const int n, const int line)
{
    // Throw an assertion when faulty parameters are supplied.
    assert(line >= 0 && line < n && n > 0);

    const int square = n * n;
    int       i      = 0;

    // Simple case: The first line of a spiral.
    if (line == 0)
    {
        for (i = 0; i < n; i++)
        {
            printf("%02d ", (square - 1) - i);
        }
    }

    // Simple case: The last line of a spiral.
    else if (line == (n - 1))
    {
        for (i = 0; i < n; i++)
        {
            printf("%02d ", square - (3 * n) + 2 + i);
        }
    }

    // Complex case: Line with other inner spirals.
    else
    {
        // Print the first character.
        printf("%02d ", square - (4 * n) + 4 + (line - 1));

        // Print a line of the rest
        DrawSpiralLine(n - 2, line - 1);

        // Print the last character
        printf("%02d ", (square - 1) - n - (line - 1));
    }
}

void DrawSpiral(const int n)
{
    int i = 0;

    // Draw the lines of the spiral.
    for (i = 0; i < n; i++)
    {
        DrawSpiralLine(n, i);
        printf("\n");
    }
}

int main(void)
{
    DrawSpiral(6);
    return 0;
}

DrawSpiral(6) will draw something like:

35 34 33 32 31 30
16 15 14 13 12 29
17 04 03 02 11 28
18 05 00 01 10 27
19 06 07 08 09 26
20 21 22 23 24 25

Let me know if there's anything specific you want to know, I think it's pretty straight forward. (Recursive solutions are often pretty easy to read)

Gonbe 32 Newbie Poster

Something I made for a similar question in "C". Checks lines of text as opposed to words.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
#include <ctype.h>

bool IsPalindrome (const char *string, const int size)
{
    assert (size >= 0);

    // A word consisting of one letter or less is palindrome.
    if (size <= 1)
    {
        return true;
    }
    // non-letters may be skipped.
    else if (!isalpha(string[0]))
    {
        return IsPalindrome(string + 1, size - 1);
    }
    // the same goes for the end
    else if (!isalpha(string[size - 1]))
    {
        return IsPalindrome(string, size - 1);
    }
    // The first and final character are both letters. These must be equal.
    else
    {
        return (tolower(string[0]) == tolower(string[size - 1])) && IsPalindrome(string + 1, size - 2);
    }
}

int main(void)
{
    const char* tests[] = {
        "Bush saw Sununu swash sub.",
        "Do, O God, no evil deed! Live on! Do good!",
        "This is a random text",
        "Flee to me, remote elf.",
        "No, I told Ed \"lotion.\"",
        "Never gonna give you up, never gonna let you down, Never gonna run around and desert you."
    };

    const int testsCount = sizeof(tests) / sizeof(char*);
    int i = 0;

    for (i = 0; i < testsCount; i++)
    {
        if (IsPalindrome(tests[i], strlen(tests[i])))
        {
            printf("\"%s\" is a palindrome!\n", tests[i]);
        }
    }

    return 0;
}
PrimePackster commented: Again! No spoon feeding on DANIWEB +0
Gonbe 32 Newbie Poster

Hi,

I'm not sure where to start so I'll start from the beginning and type as I go through your code.

When checking your command-line parameters you have a series of if statements, but entry of one does not lock out the rest; this is undesire in your case as it will continue to attempt opening a file and perform other activities. You also don't need the argv[1] check that way. I am also not sure why the entire construct is in a do-while loop. Could you explain this? I've removed it for now as I didn't see the need for it. This means I've modified main to the following:

int main(int argc, char* argv[])
{
    ifstream inFile;
    node    *lists[MAX_CELLS] = { NULL };
    int      count            = -1;
    bool     result           = true;

    // Check the amount of command-line arguments.
    if (argc != 2)
    {
       cerr << "Command line arguments not valid!\n";
    }

    // A correct amount of command-line parameters were supplied.
    else
    {
        // Attempt to open the file with the file name supplied as a command-line parameter.
        inFile.open(argv[1]);

        // Opening failed.
        if (!inFile)
        {
            cerr << "The input data file does not exist or cannot be opened!\n";
        }
        // Opening was a success!
        else
        {
            cout << "Results for input file \"" << argv[1] << "\":\n";
            ReadInFile(inFile, lists, count);
        }
    }

    return 0;
}

The next point of interest seems to be the "ReadInFile" function. In the first part you're reading integers from the file, and for …

Gonbe 32 Newbie Poster

"isbn" is a private member and is a string. The class has an overloaded == operator so you can use that directly

if (item == item2)

or, if that doesn't only compare the ISBN, you can use the "same_isbn" function.

if (item.same_isbn(item2))
Gonbe 32 Newbie Poster

Because you want the pointer address to change if something was added. Say you have your list and it is empty. This means the pointer is NULL. After calling the "addNode" function it adds a node to it and you'll want the pointer you passed to the function to be the address of that node.

-edit-

Say your function was this:

// Function to add a node to the linked list. data must be a C-string.
void addNode(node* list, const char data[])
{
    // The list is empty.
    if (list == NULL)
    {
        list = (node*) malloc (sizeof(node));
        list->next = NULL;
        strncpy(list->data, data, DATA_SIZE);
    }
    else
    {
        addNode(list->next, data);
    }
}

And you'd call it like:

node* list = NULL;
addNode(list, "hello");

// What would 'list' be now?
Gonbe 32 Newbie Poster

There's multiple things I'd change. First of all you're asking for input outside of the do-while loop you have in "choice". The user won't get the chance to re-enter input. I've moved that inside it.

Then, the head of your linked list is created on the stack in main, while you (attempt to) create the rest on the heap. You should make everything on the heap to keep things consistent for when you want to free stuff. You do later malloc a node and assign that to the head. I've removed the one in main.

You don't describe what you want your application to do.. So I am making assumptions here. I think you only want to loop asking for input as long as the user doesn't select option 1? And once that option is chosen the "enter" function asks all input after which the application finishes?

The enter function is a mess, so i've modified it based on the above..

The "not responding" part probably happens due to the scanset you are using in the second scanf. The first one reads an integer and will leave a newline, which is exactly what the scanset of the second scanf looks for. Add a space at the start of the format string to skip whitespaces at the beginning. (assuming this is okay for your program, you should have been more detailed if not..)

Results in:

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

// Includes the NULL character.
#define DATA_SIZE (20)

struct …
Gonbe 32 Newbie Poster

and i wonder if you can do it. :-)

I have little doubt that I could, but I don't think I will just for the sake of proving you wrong. I've removed the downvote though even though the point made stands; christmas magic, I guess.

Gonbe 32 Newbie Poster

nVar is converted to a double which results in a temporary variable which is an rvalue. A quick search for rvalues and lvalues yields the following definition:

You can think of an lvalue as an object that has a name. All variables, including nonmodifiable (const) variables, are lvalues. An rvalue is a temporary value that does not persist beyond the expression that uses it.

A better source of reading is this.

You may not associate a temporary variable with a reference, but you may with a const reference. (The last extends the lifetime of the temporary variable)

Would link a section of the specification, but seems to troublesome to go through that :<. Should look into it yourself though, it'll be in there.

Gonbe 32 Newbie Poster

As mentioned above, include string.h and replace "trainset" with "struct trainset" on line 34. Then, as far as your actual question goes:

What needs to be done to link it?

You're not linked the items you created to the root node. Add

root->next = first_train;

Also, you're assigning names to the wrong items.

strncpy(first_train->name, "Uncle Bobs train set", 50);

should be the second train.

Finally, in your loop condition you should check if the current item is not null, as that is the one you're dereferencing.

These changes result in the following:

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

struct trainset
{
    char name[50];
    int price;
    struct trainset *next;
};

void show_list(struct trainset *list);

int main (void){

    struct trainset *root;

    root = (struct trainset *)malloc(sizeof(struct trainset));
    strncpy(root->name, " ", 50);
    root ->price = 0;
    root ->next = 0;

    struct trainset *first_train;
    first_train = (struct trainset *) malloc(sizeof(struct trainset));
    root->next = first_train;
    strncpy(first_train->name, "Fantasy Train Set", 50);
    first_train->price = 129;
    first_train->next = NULL;

    struct trainset *second_train;
    second_train = (struct trainset *)malloc(sizeof(struct trainset));
    first_train->next = second_train;
    strncpy(second_train->name, "Uncle Bobs train set", 50);
    second_train ->price = 69;
    second_train ->next = NULL;

    struct trainset *third_train;
    third_train = (struct trainset *)malloc(sizeof(struct trainset));
    second_train->next = third_train;
    strncpy(third_train ->name, "Budha Bread Train", 50);
    third_train ->price = 169;
    third_train ->next = NULL;

    show_list(root);
    return 0;
}

void show_list(struct trainset *list)
{
    while(list != NULL)
    {
        printf("train set name: \"%s\", price: %d.\n", list->name, list->price);
        list = list->next;
    }
}
Gonbe 32 Newbie Poster
#include <iostream>
#include <vector>

using namespace std;

void PrintOptions (int amount, const int coinOptions[], const int coinCount, vector<int> paid = vector<int>());


void PrintOptions (int amount, const int coinOptions[], const int coinCount, vector<int> paid)
{
    // There's nothing left to pay!
    if (amount == 0)
    {
        // Show what we've paid to achieve this.
        for (int i = 0; i < paid.size(); i++)
        {
            cout << paid[i] << " ";
        }
        cout << endl;
    }

    // Still something to try to pay with.
    else if (coinCount > 0 && amount > 0)
    {
        // Try to pay as much big coins as possible, starting at 0 of them.
        do
        {
            // Print the options for the remaining amount, without the biggest coin and "paid" containing what we paid so far.
            PrintOptions(amount, coinOptions + 1, coinCount - 1, paid);

            // Pay another one of the biggest coin.
            paid.push_back(coinOptions[0]);
            amount      -= coinOptions[0];
        }
        while (amount >= 0);
    }
}

int main()
{
    const int COINS[] = { 5, 2, 1 };

    PrintOptions(10, COINS, sizeof(COINS) / sizeof(int));

    return 0;
}
Gonbe 32 Newbie Poster

Show the code you have for reading the entire content and I'll go from there.

Gonbe 32 Newbie Poster

That selection is done in the application itself, right? So just ask for a student ID and display the data of the user that has that ID. (You mentioned you can read the data just fine, so looking it up should be trivial)

Gonbe 32 Newbie Poster

What is the type of DESTINATION?

The reason being a function takes unsigned char DESTINATION[3].

Gonbe 32 Newbie Poster
#include <map>
#include <string>
#include <iostream>

using namespace std;

struct PoiDetails
{
   int x;
   string s;
};

int main()
{
    PoiDetails oBj;
    multimap<string, PoiDetails> vName;

    // Add the contents.
    oBj.x = 1; oBj.s = "str1";
    vName.insert(pair<string, PoiDetails>("Jhon", oBj));

    oBj.x = 2; oBj.s = "str2";
    vName.insert(pair<string, PoiDetails>("Ben F", oBj));

    oBj.x = 3; oBj.s = "str3";
    vName.insert(pair<string, PoiDetails>("Shown", oBj));

    oBj.x = 4; oBj.s = "str4";
    vName.insert(pair<string, PoiDetails>("peter", oBj));

    oBj.x = 5; oBj.s = "str5";
    vName.insert(pair<string, PoiDetails>("juk", oBj));

    oBj.x = 6; oBj.s = "str6";
    vName.insert(pair<string, PoiDetails>("peter", oBj));

    // Show the contents.
    for (multimap<string, PoiDetails>::iterator it = vName.begin(); it != vName.end(); it++)
    {
        cout<<"Detail " << distance(vName.begin(), it) << " ";
        cout << it->first << "\t";
        cout <<"x = "<< it->second.x <<"\t";
        cout <<"s = "<< it->second.s <<"\n";
    }

    return 0;
}
Gonbe 32 Newbie Poster

nearly, couldn't get it to work with letters, the 'D' seems to get missed out

What do you mean?

When I add something like the following after my code:

for (int i = 0; i < DESTINATION_SIZE; i++)
    std::cout << (int)DESTINATION[i] << std::endl;

You'd get the following output:

57
4
125

Which is what I'd expect.

Gonbe 32 Newbie Poster

Even if that's not possible, you could change it to something like this:

#include <sstream>
#include <iostream>

const int SOURCE_SIZE      = 8;
const int DESTINATION_SIZE = (SOURCE_SIZE + 1) / 3;

int main()
{
    std::stringstream ss;
    int value;

    unsigned char SOURCE     [SOURCE_SIZE]      = {'3', '9', ' ', '0', '4', ' ', '7', 'D'};
    unsigned char DESTINATION[DESTINATION_SIZE] = { 0 };

    ss << std::hex;
    ss.write((const char*)SOURCE, SOURCE_SIZE);

    for (int i = 0; ss >> value; i++)
        DESTINATION[i] = value;

    return 0;
}

-edit-
Modified it so the destination size is based on the source size.. Just set source to 8 for your example, destination will be 3 then.

Gonbe 32 Newbie Poster
#include <sstream>
#include <iostream>

int main()
{
    const char *src = "39 04 7d";
    int value;
    std::stringstream ss;

    ss << std::hex << src;

    while (ss >> value)
        std::cout << value << std::endl;

    return 0;
}

-edit-

Added a return 0. (Blame deceptikon's code for lacking that, got lazy and took that as base)
Also works with upper case. (e.g. "FF" vs "ff")

Gonbe 32 Newbie Poster

You could try something like this:

#include <iostream>
#include <algorithm>
using namespace std;

const int AMOUNT_OF_GRADES = 5;

double Average (const double array[], const int count)
{
    double result = 0;

    for (int i = 0; i < count; i++)
    {
        result += array[i] / count;
    }

    return result;
}


double Sum (const double array[], const int count)
{
    if (count <= 0)
    {
        return 0;
    }
    else
    {
        return array[0] + Sum(array + 1, count - 1);
    }
}


int main()
{
    double grades[AMOUNT_OF_GRADES] = { 3, 2.2, 2, 5, 1.8 };

    // Sort the array.
    // The lowest will be at index 0 and the highest at index AMOUNT_OF_GRADES - 1.
    sort(grades, grades + 5);

    cout << "Lowest: "  << grades[0] << endl;
    cout << "Highest: " << grades[AMOUNT_OF_GRADES - 1] << endl;
    cout << "Average: " << Average(grades + 1, AMOUNT_OF_GRADES - 2) << endl;
    cout << "Total: "   << Sum(grades, AMOUNT_OF_GRADES) << endl;

    return 0;
}

Let me know if anything is unclear.

-edit-
You could also define your average function like this:

double Average (const double array[], const int count)
{
    return Sum(array, count) / count;
}

I didn't do that because this is more vulnerable to arithmetic overflow. (which is just theoretical in this case.. a sum of scores that is bigger than what a double can hold won't realistically happen)

I also defined AMOUNT_OF_GRADES while it's not needed. I thought it would be clearer. You could remove it …

Gonbe 32 Newbie Poster

Quick fix

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    int input;
    int random;

    cout << "             VIRTUAL DICE 1.0" << endl;
    srand((unsigned)time(0));

    do
    {
        cout << "Enter 1 to roll and 0 to quit: ";
        cin >> input;

        if (input == 1)
        {
            // Generate a number 1 - 6
            random = (rand() % 6) + 1;

            switch(random)
            {
                case 1:
                    cout << " -------- " << endl;
                    cout << "|        |" << endl;
                    cout << "|    O   |" << endl;
                    cout << "|        |" << endl;
                    cout << " -------- " << endl;
                    break;
                case 2:
                    cout << " -------- " << endl;
                    cout << "|O       |" << endl;
                    cout << "|        |" << endl;
                    cout << "|       O|" << endl;
                    cout << " -------- " << endl;
                    break;
                case 3:
                    cout << " -------- " << endl;
                    cout << "|       O|" << endl;
                    cout << "|    O   |" << endl;
                    cout << "|O       |" << endl;
                    cout << " -------- " << endl;
                    break;
                case 4:
                    cout << " -------- " << endl;
                    cout << "|O      O|" << endl;
                    cout << "|        |" << endl;
                    cout << "|O      O|" << endl;
                    cout << " -------- " << endl;
                    break;
                case 5:
                    cout << " -------- " << endl;
                    cout << "|O      O|" << endl;
                    cout << "|    O   |" << endl;
                    cout << "|O      O|" << endl;
                    cout << " -------- " << endl;
                    break;
                default:
                    cout << " -------- " << …
Gonbe 32 Newbie Poster

I am not really sure what you mean by that. Could you elaborate and/or provide an example?

Gonbe 32 Newbie Poster

3 year old thread, but only noticed after already writing the below, muh!

#include <iostream>

using namespace std;

void PrintStarLine(const int size)
{
    if (size > 0)
    {
        cout << "*";
        PrintStarLine(size - 1);
    }
    else
    {
        cout << endl;
    }
}

void PrintStarTriangle(const int size)
{
    if (size > 0)
    {
        PrintStarLine(size);
        PrintStarTriangle(size - 1);
    }
}

int main ()
{
    PrintStarTriangle(10);

    return 0;
}
Gonbe 32 Newbie Poster

You shouldn't assign NULL to non-pointer values; the representation of pointer values is implementation defined. For most compilers the conversion will result NULL being converted to 0 as int meaning in your case it's both NULL and 0, but again, don't do it..

#include <iostream>

using namespace std;

int main ()
{
    int num = NULL;

    if(num == 0)
        cout << "num is zero" << endl;

    if(num == NULL)
        cout << "num is NULL" << endl;

    return 0;
}
Gonbe 32 Newbie Poster

The printf statement in main does the second?

Somewhat related, I found another (iterative) fibonacci function lately that is interesting:

long int fib(unsigned long int n) {
   return lround((pow(0.5 + 0.5 * sqrt(5.0), n) - 
                  pow(0.5 - 0.5 * sqrt(5.0), n)) / 
                 sqrt(5.0));
}
Gonbe 32 Newbie Poster

That's somewhat complex for someone learning C. An algorithm I'd use for parsing these kind of formula's would be the Shunting-yard algorithm by Dijkstra. The article contains example code for C too.

Gonbe 32 Newbie Poster

Wouldn't something like this be easier?

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

bool ParsePayRate(const char *text, int* dollars, int* cents)
{
    unsigned int consumed = 0;
    return ((sscanf(text, "%d.%2d%n", dollars, cents, &consumed) == 2) && (consumed == strlen(text)));
}

bool ParseHours(const char *text, int* hours)
{
    unsigned int consumed = 0;
    return ((sscanf(text, "%d%n", hours, &consumed)) && (consumed == strlen(text)));
}

int main(int argc, char *argv[])
{
    int dollars, cents, hours;

    if (argc != 3)
    {
        printf("Usage: %s <payrate> <hours>\n", argv[0]);
    }
    else
    {
        // Parse the pay rate.
        if (ParsePayRate(argv[1], &dollars, &cents))
        {
            printf("Pay rate successfully parsed. Dollars: %d, cents: %d.\n", dollars, cents);
        }
        else
        {
            printf("Invalid pay rate.\n");
        }

        // Parse the hours.
        if (ParseHours(argv[2], &hours))
        {
            printf("Hours successfully parsed. Hours: %d.\n", hours);
        }
        else
        {
            printf("Invalid hours.\n");
        }
    }

    return 0;
}
Gonbe 32 Newbie Poster

A while ago I started to made a couple of simple tree-operations for a BST. It was made for C though and it wasn't quite finished yet. Function descriptions and such are missing and the final interface is missing. I also wanted to add a mechanism to add variable node content but didn't get to do it. Anyway, it contains insertion and the code itself is commented well enough I think:

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

typedef int NodeValue;

struct Node
{
    NodeValue    value;
    struct Node* left;
    struct Node* right;
};

struct Queue
{
    const struct Node* node;
    struct Queue* next;
};


// Tree operation functions.
bool               Insert             (const NodeValue value, struct Node** const tree);
void               Delete             (const NodeValue value, struct Node** const tree);
const struct Node* Search             (const struct Node* const tree, const NodeValue value);
bool               Min                (const struct Node* const tree, NodeValue* const value);
bool               Max                (const struct Node* const tree, NodeValue* const value);
const struct Node* InOrderSuccessor   (const struct Node* tree);
const struct Node* InOrderPredecessor (const struct Node* tree);
int                CountDescendants   (const struct Node* const tree);
bool               NodesOnLevel       (struct Node* const tree, const int level, struct Queue** const queue);

// Traversal functions.
void               PreOrderTraversal  (const struct Node* const tree, void (*callback)(const void* const));
void               InOrderTraversal   (const struct Node* const tree, void (*callback)(const void* const));
void               PostOrderTraversal (const struct Node* const tree, void (*callback)(const void* const));
bool               LevelOrderTraversal(      struct Node* const tree, void (*callback)(const void* const));

// Tree property functions.
int                Height             (const struct Node* const …
Gonbe 32 Newbie Poster

Yeah a struct is right for that. Searching data "based on a struct" is troublesome if you don't want the function to do any assumptions on what the struct looks like though. What you could do is define functions for any type of search "type". For example a "SearchByFirstName", "SearchById", and so on. For some, like first name, you'll likely want to return a vector as the search can yield multiple results but an ID is unique so it will return at most 1 result.

Gonbe 32 Newbie Poster

The code will be like this

#include <iostream>

int main ()
{
    std::cout << "Nice _quality_ necro-post.\n";
    return 0;
}
Gonbe 32 Newbie Poster

You didn't supply enough information about your application for me to answer that. I'd change my design in a way where I have no need to be able to address a struct member based on a variable name. (e.g. a design in which functions will know what a struct looks like) In essence it would become somewhat like Lucaci Andrew posted. Are you trying to setup everything super generic that you want to address things based on a variable? If that's what you want I'd probably reconsider the use of a struct and design something more capable of doing what you want. (which could ofcourse contain structs)

Gonbe 32 Newbie Poster
#include <stdio.h>
#include <windows.h>

void PrintTwinkleSection(const int handsomeTwinkleOffset, const char* amazingTwinkle, const int fineTwinkleLength)
{
    int lovelyTwinkleIndex = 0;

    for (lovelyTwinkleIndex = 0; lovelyTwinkleIndex < fineTwinkleLength; lovelyTwinkleIndex++)
    {
        putc(amazingTwinkle[(lovelyTwinkleIndex + handsomeTwinkleOffset) % fineTwinkleLength], stdout);
    }
}


int main (void)
{
    const char* BEAUTIFUL_TWINKLE = "_,.-'-.,_";
    const char* ANGELIC_TWINKLE_TEXT = "*T*W*I*N*K*L*E*S*";

    int exquisiteTwinkleOffset  = 0,
        attractiveTwinkleSize   = strlen(BEAUTIFUL_TWINKLE),
        alluringTwinkleTextSize = strlen(ANGELIC_TWINKLE_TEXT);

    for(;;)
    {
        PrintTwinkleSection(exquisiteTwinkleOffset, BEAUTIFUL_TWINKLE, attractiveTwinkleSize);

        printf(ANGELIC_TWINKLE_TEXT);

        PrintTwinkleSection(exquisiteTwinkleOffset + alluringTwinkleTextSize, BEAUTIFUL_TWINKLE, attractiveTwinkleSize);

        exquisiteTwinkleOffset = (exquisiteTwinkleOffset + 1) % attractiveTwinkleSize;
        Sleep(50);

        printf("\r");
    }

    return 0;
}
Gonbe 32 Newbie Poster

A static class member exists on a class level as opposed to non-static class members that exist on an object level. For example, what you can do with s_b but not with b is access it without having an "A" object, as it's not part of an object but of a class. Every object will have it's own "b" though.

Gonbe 32 Newbie Poster

The map thing I mentioned:

#include <string>
#include <map>
#include <iostream>

using namespace std;

class Person
{
    public:
        Person(const int id, const string firstName, const string lastName, const string address, const string phone) : _id(id)
        {
            _data["firstName"] = firstName;
            _data["lastName" ] = lastName;
            _data["address"  ] = address;
            _data["phone"    ] = phone;
        }
        string operator() (const string field);

    private:
        int _id;
        map<string, string> _data;
};

string Person::operator() (const string field)
{
    map<string, string>::const_iterator it;

    it = _data.find(field);

    if (it != _data.end())
    {
        return it->second;
    }
    else
    {
        // Exception?
        return "";
    }
}

int main()
{
    Person example(1, "Bob", "Saget", "House 01", "1234");

    if (example("firstName") == "Bob")
    {
        cout << "Bob saget detected.\n";
    }
    else
    {
        cerr << "Bob saget not found.\n";
    }

    return 0;
}

But yeeeaahh.. Shouldn't want this :< Will also become more complex if you want it to contain random datatypes.

Gonbe 32 Newbie Poster

He doesn't only want the value to match against to be stored into a variable, but also the struct field that is matched against. So in your example he'd want something like this:

#include <vector>
#include <string>
using namespace std;
struct person{
    string fname, lname;
    int age;
};

int main(){
    vector<person> list;
    // do stuff with your persons;

    string searchValue = "JohnDoe",
           searchField = "fname";

    for (vector<person>::iterator it=list.begin();it!=list.end();it++){
        // Do "(*it).fname == "JohnDoe"" because searchValue = JohnDoe and searchField is fname.
        {
            //do stuff with your person...
        }
    }
    return 0;
}

You can't overload the dot operator either, otherwise you could try to make something that comes kind-of-close with some internal additions.

Gonbe 32 Newbie Poster

*Hands Ranjan_1 the "Post-of-the-day badge".

Gonbe 32 Newbie Poster

You could reference all .o files as well, although I don't see the advantage of that over referring to a single .a file.

Gonbe 32 Newbie Poster

hey ####tards, I wanted to know if I could parse a single integer from a string that contains multiple substrings** and integers -.-

Hey clown. Glad to hear you no longer want to know.

Gonbe 32 Newbie Poster

Are you sure you want a different file every time the program is run? It seems to me you actually want the same textfile everytime, otherwise you wouldn't need textfiles in the first place. (You could just store things in memory as you don't have to "remember" it in between executions anyway)

There's also some oddities in the code. For example:

for ( int i =0 ; i<1 ; i++)

I won't be going over these I guess, but it's probably good to look over it closely at some point. I assume you did the above loop to somehow determine the number of the file you want to create at some point.

First thing I'd do is to create a structure (or class, but I assume you don't want classes for this) for information that is stored on a per client basis. I'll be using the datatypes you used, but this is something that could be improved upon.

struct ClientInfo
{
    string name;
    string mail;
    string address;
    string password;
    int mobile;
    int phone;
};

Something you could do next is dealing with the file I/O. To keep things simply it's probably best to start with reading the contents of the file at startup, and then writing the updated contents back to the file when closing. Depending on your demands exactly you might not ever end in a proper fashion though. So instead I guess something that's sort of easy would be to read the file at …

Gonbe 32 Newbie Poster

I'd say an ".a" file. An object file typically contains object code for a single source file, while an ".a" file contains multiple of them. (It is an archive of multiple .o files) So both did not involve any linking yet. Also note that this is a static library as oppposed to a shared library that are also quite common (.dll, .so). It means the machine code from the library will be copied into the final executable while with a shared library a table of stored and at startup the required functions are loaded into memory. (dynamic linking)

Gonbe 32 Newbie Poster

Your question is quite vague to me. Also the assignment isn't fun enough for me to go try it and you don't provide any code whatsoever to fix. You could simply use a textfile as a database which stores the account number and password per line. Then at startup you could read this file into memory, or lookup the account number in the file everytime it's requested.

Gonbe 32 Newbie Poster

Example of b

#include <stdio.h>

int Highest (const int l, const int r)
{
    return ((l > r) ? l : r);
}

int Lowest (const int l, const int r)
{
    return ((l < r) ? l : r);
}

void FindMinMax (const int A[], const int n, int* const min, int* const max)
{
    int curMin = 0, curMax = 0;

    if (n == 1)
    {
        (*min) = A[0];
        (*max) = A[0];
    }
    else if (n > 1)
    {
        curMin = A[0];
        curMax = A[0];

        FindMinMax(A + 1, n - 1, min, max);

        (*min) = Lowest ((*min), curMin);
        (*max) = Highest((*max), curMax);
    }
}

int main(void)
{
    int example[] = { 23, 488, 1, 2930, 99, 102 };
    int low, high;

    FindMinMax(example, sizeof(example) / sizeof(int), &low, &high);
    printf("lowest: %d, highest: %d\n", low, high);

    return 0;
}

Found "a" too boring so didn't bother doing that.. Could maybe help if you start on it so I only have to finish/correct it.

deceptikon commented: The OP's question falls under our homework rule. -2
nitin1 commented: not even single effort seen , yet you give the code instead of advices +0
Gonbe 32 Newbie Poster

Oops, in my post I meant you're trying to reference the "firstname" field instead of "jimmy". It doesn't change much for the way I interpreted it though; it's not possible to select a struct member by variable. If you really insists on something like this maybe changing the structs to map's is something to consider. (Or add a map to the struct that contains all the strings)

Gonbe 32 Newbie Poster

You'll want to check if you go out of bounds. For example, you can do this in your move function:

#include <iostream>
#include <stdlib.h> //For system()
#include <conio.h> //For getche()
#include <time.h>
using namespace std;
//You can modify these numbers but don't delete these constants or this starting code will not work
const int MAX_HEIGHT = 20; //The height of the grid
const int MAX_WIDTH = 40; //The width of the grid
/********************************************************************
 * Class: PickUpGame
 * Purpose: To store the grid and the current x and y position of the
 * user. Also has memeber functions to intialize the grid and print it.
 * Allows the user to move around the grid but provides no out of
 * bounds checking.
 ********************************************************************/
class PickUpGame
{
protected:
      char Screen[MAX_HEIGHT][MAX_WIDTH]; //The grid to print to the screen
      int xPos, yPos; //The current x and y position of the users cursor on the grid
public:
      //Constructor that will intialize the screen and x and y positions
      PickUpGame() : xPos(0), yPos(MAX_WIDTH - 1)
      {
           SetupScreen(); //Initalize the grid
      }
      //Initialize the screen with all '.' characters and set the intial user cursor position on the grid
      void SetupScreen()
      {
           for(int height = 0; height < MAX_HEIGHT; height++) {
                for(int width = 0; width < MAX_WIDTH; width++) {
                     Screen[height][width] = '.'; //Initialize each grid position
                }
           }
           Screen[xPos][yPos] = '<'; //Set the users initial cursor position
      }
      //Print the grid to the screen
      void Print()
      {
           for(int height = 0; height < MAX_HEIGHT; height++) …
Gonbe 32 Newbie Poster

The double dollar sign is used to set address a variable variable name, right? This is not possible in C++ and in this context I don't think it's what you want. You want the address a struct member called "jimmy" here? You'd probably rather want a "name" struct member and compare the value of it with "jimmy".