Gonbe 32 Newbie Poster

Programmer? Hell no. I'm a professional figure skater.

Gonbe 32 Newbie Poster
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>

#define LINE_WIDTH  (15)
#define BUFFER_SIZE (1024)

char* word_wrap (
        char*              buffer,
        const unsigned int buffer_sz,
        const char*        string,
        const unsigned int string_len,
        const unsigned int max_line_width)
{
    assert(buffer         != NULL &&
           buffer_sz      > 0     &&
           string         != NULL &&
           string_len     > 0     &&
           max_line_width > 0);

    unsigned int i              = 0,
                 cur_line_width = 0;
    int          last_space     = -1;

    // Go past every character of the string, as long as
    // we'd have buffer space to store it in.
    for (i = 0; i < string_len && i < buffer_sz - 1; i++)
    {
        buffer[i] = string[i];      // Copy the character to our buffer.
        cur_line_width++;           // Our line just grew by one.

        if (isspace(buffer[i]))     // Keep track of our last whitespace.
            last_space = i;

        // The max line length is reached, and we've found a whitespace up until this point.
        if (cur_line_width > max_line_width && last_space >= 0)
        {
            buffer[last_space]  = '\n';           // Replace the space with a newline.
            cur_line_width      = i - last_space; // And update the length of the new line.
        }
    }

    // The string was copied. Terminate the buffer with a NULL character.
    buffer[i] = '\0';

    return buffer;
}

int main(void)
{
    char* test = "This function takes a string and an output buffer and a desired width. It then copies the string to the buffer, inserting a new line character when a certain line length is reached. If the end of the line is in the middle …
Gonbe 32 Newbie Poster

What is there to explain? malloc (attempts to) allocate a given amount of memory on the heap. It doesn't really know (or cares) what you're going to put there so it returns a void pointer so you'll have to cast it to a pointer matching the data you're putting in it. (atleast if you want to dereference it for example)

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

int main(void)
{
    int* heap_int = NULL;

    // Allocate memory for a single integer.
    heap_int = (int*) malloc(sizeof(int));

    if (heap_int == NULL)
        printf("Memory allocation failed.\n");
    else
    {
        printf("Memory was successfully allocated.\n");

        // Free the memory again.
        free(heap_int);
    }
    return 0;
}
Gonbe 32 Newbie Poster

Not having a compiler handy, so treat the following as kind-of pseudo code, but if performance is no requirement you could define it as

bool isMono(const tNode* t)
{
    if (t == NULL) 
        return true;
    else
        return tsearch(t->info, t->left) == NULL && tsearch(t->info, r->right) == NULL && isMono(t->left) && isMono(r->right);
}

(assuming tsearch on an empty tree results in a NULL pointer)

Gonbe 32 Newbie Poster
normally an integer datatype hold 2 byes of memory.If Int is declared it holds 2 bytes by default.

This is not true. The amount of bytes an integer takes up depends on the supported word size of the used CPU and there is no "default" specified in the specification. 32-bit or 64-bit are most common on desktops and I've personally only encounter 8 and 16 bit integers on embedded systems.

&arr

This is a pretty common misconception. &arr represents the memory address of the first element in arr. (More precisely the memory address of the array, which is the memory address of the first element) and in this case that expression would be of type int(*)[2]. arr itself does not have a memory address. When used in an expression it is implicitly converted to a pointer type however, so int* in this case, representing the memory address of the first element in arr. Hence arr == &arr == &arr[0]. (the resulting memory addresses, the types of the expressions differ)

arr + 1 which means 2 bytes

As stated earlier arr would be implicitly converted to type int* so doing arr + 1 yields the memory address of the first element in arr (represented by arr) plus 1 time sizeof(int) amount of bytes. (represented by + 1) In this case this would be the memory address of the second element in arr.

&arr +1 means arr[]=> 2 bytes for arr and 2 bytes for …
Gonbe 32 Newbie Poster

Or meh, question is poor and no effort is shown, but can't say I care for a task this small. Empower me with your downvotes, mortals! :<

#include <stdio.h>

int main(void)
{
    char string[]        = "f a1 2 5 ffffffde 23 fffffff1 4 b0";
    const char* remove   = "ffffff";
    const int remove_len = strlen(remove);
    char* offset         = NULL;

    while (offset = strstr(string, remove)) {
        strcpy(offset, offset + remove_len);
    }
    printf("Result: \"%s\".\n", string);

    return 0;
}
rubberman commented: No mortals here! :-) +12
Gonbe 32 Newbie Poster
#include <stdio.h>

int main(void)
{
    const char* string_before = "f a1 2 5 ffffffde 23 fffffff1 4 b0";
    const char* string_after  = "f a1 2 5 de 23 f1 4 b0";

    printf("The C-code resulted in: \"%s\".\n", string_after);

    return 0;
}
Gonbe 32 Newbie Poster

Relevant fragements from the C(99) specification (http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf):

6.2.4 Storage durations of objects
-----------------------------------

The lifetime of an object is the portion of program execution during which storage is
guaranteed to be reserved for it. An object exists, has a constant address,25) and retains
its last-stored value throughout its lifetime.26) If an object is referred to outside of its
lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when
the object it points to reaches the end of its lifetime.


6.3.2.3 Pointers (Point 6)
--------------------------

Any pointer type may be converted to an integer type. Except as previously specified, the
result is implementation-defined. If the result cannot be represented in the integer type,
the behavior is undefined. The result need not be in the range of values of any integer
type.


7.1.4 Use of library functions
-------------------------------

Each of the following statements applies unless explicitly stated otherwise in the detailed
descriptions that follow: If an argument to a function has an invalid value (such as a value
outside the domain of the function, or a pointer outside the address space of the program,
or a null pointer, orapointer to non-modifiable storage when the corresponding
parameter is not const-qualified) or a type (after promotion) not expected by a function
with variable number of arguments, the behavior is undefined.
Gonbe 32 Newbie Poster

You are comparing indexes to string values. In addition there seemed to be some logic mistakes. Here's an attempt to fix them for you:

void fold(char s[], int l)
{
    int i, j, foldHere;
    i = j = 0;

    foldHere = FOLDLENGTH;

    while (i < l)
    {
        // We are currently on a non-space symbol.
        if (s[i] != ' ')
        {
            // Copy our index to 'j'.
            j = i;

            // Go to the next space-symbol (or to the end of the string)
            while (s[j] != ' ' && j < l) {
                putchar(s[j]);
                ++j;
            }

            // We're not at the end of the string and the fold marker was passed.
            // This means there are words following, print the newline now.
            // Future improvement: check if the following characters are non-whitespace characters.
            if (j < l)
            {
                if (j >= foldHere) {
                    putchar('\n');
                } else {
                    putchar(s[j]);
                }
            }

            // Continue after the marker.
            i = j + 1;
        }
        else
        {
            if (i == foldHere)
                putchar('\n');
            else
                putchar(s[i]);
            ++i;
        }
    }
}

I wasn't fully sure what you were trying to do however. Here's another approach that might be easier to read:

void fold(char str[], int length, int fold_index)
{
    // Assuming the parameters are "correct".
    int i;

    // Everything up until fold_index can 'safely' be printed.
    for (i = 0; i < fold_index; i++)
        putchar(str[i]);

    // Would you want to check for other whitespace characters too?
    while(str[i] != ' ' && i < length) …
Gonbe 32 Newbie Poster

The factorial of a positive integer n, n!, is 1 * 2 * 3 * ... * n for n > 0 and 1 for n = 0. Would take you about 1 second to find on google.

The simple case is when n = 0, you simply return 1.

if (n == 0)
    return 1;

Then for other cases we want to express the problem of calculating the factorial using a smaller version of the same problem so we can solve it recursively. It's easy to see that fac(n) = n * fac(n - 1).

else
    return n * fac(n - 1);
Gonbe 32 Newbie Poster
Thanks man! but can I do by using Pass by Reference? not Pass by Pointers?

Not in C, that's a C++ feature. Closest thing you could do is make the pointers you pass const. (e.g float* const res)

Gonbe 32 Newbie Poster
#include <stdio.h>

void A(float* res)
{
    float a, b;
    printf("Enter Numbers A: \n");
    scanf(" %f %f",&a,&b);
    (*res) = a+b;
}

void B(float* res)
{
    float a, b;
    printf("Enter Numbers B: \n");
    scanf(" %f %f", &a, &b);
    (*res) = a + b;
}

int main(void)
{
    float total,Ares,Bres;

    A(&Ares);
    B(&Bres);

    total= Ares + Bres;
    printf("A + B = %.2f \n",total);

    return 0;
}
jandanielsaclolo commented: Thanks! +0
Gonbe 32 Newbie Poster

Hmm, so you want to count the amount of times an integer is present in a matrix without knowing upfront what integers can be in there? I don't think there's a very beginner-friendly solution for this. I'd probably use a map for it. Below an example:

#include <iostream>
#include <map>
#include <iomanip>

using namespace std;

int main()
{
    const unsigned int DIMENSION = 6;

    int M[][DIMENSION]= {{3,14,4,10,3,6},
                         {5,10,3,8,3,3},
                         {8,3,3,8,-3,3},
                         {10,10,-3,3,6,-3},
                         {-3,-3,6,8,5,5},
                         {6,5,5,8,5,5}};

    map<int, unsigned int> occurrences;

    // Process the matrix.
    for (int i = 0; i < 6; i++)
    {
        for (int j = 0; j < 6; j++)
        {
            occurrences[M[i][j]]++;
        }
    }

    // Show the results:
    for (map<int, unsigned int>::iterator it = occurrences.begin(); it != occurrences.end(); ++it)
    {
        cout << setw(3) << (*it).first << " ---> " << (*it).second << endl;
    }

    return 0;
}
Gonbe 32 Newbie Poster

Do you mean something like this?

#include <iostream>
#include <tuple>
#include <vector>
#include <string>

using namespace std;

int main()
{
    typedef tuple <int, string, int, int> pc_data;

    vector <pc_data> pc_vec;

    // Add some test data
    pc_vec.push_back(make_tuple(0, "never gonna ", 0, 0));
    pc_vec.push_back(make_tuple(1, "give you ", 1, 0));
    pc_vec.push_back(make_tuple(2, "up, never ", 2, 0));
    pc_vec.push_back(make_tuple(3, "stop. HAMMER TIME.", 3, 0));
    pc_vec.push_back(make_tuple(4, "gonna let you ", 4, 0));
    pc_vec.push_back(make_tuple(5, "down.\n", 5, 0));

    //Assume that pc_vec is filled with elements somewhere here...
    //This code is not working.
    //Exception : vector subject out of range because of the size dynamically changing i suppose
    for (int i=0; i < pc_vec.size(); i++)
    {
        // Test: we're going to delete the tuple of which the 3rd element (index 2) = 3.
        if(get<2>(pc_vec[i]) == 3)
        {
            pc_vec.erase(pc_vec.begin() + i);
            i--;
        }
    }

    // Result:
    for (int i = 0; i < pc_vec.size(); i++)
    {
        cout << get<1>(pc_vec[i]);
    }

    return 0;
}
Gonbe 32 Newbie Poster
string wordEasy[MAX_CHAR];

This will create an array of strings of MAX_CHAR elements. I think you're mixing up C-Strings and string objects. string wordEasy; would be what you want here.

You could do something like this:

if (difficulty == 1)
    {
        cout << "Enter a word of your choice that contains no more than 5 characters\n";
        const int MAX_CHAR = 5;
        string wordEasy;

        do
        {
            if (!wordEasy.empty())
            {
                cout << "You entered a word that contains " << wordEasy.size()<< " characters.\n";
                cout << "Enter another word that contains 5 or less characters.\n";
            }

            cin >> wordEasy;
        }
        while (wordEasy.size() > MAX_CHAR || wordEasy.empty());
    }

While I'd use a (do-)while loop here, you could ofcourse also do it with a for-loop in which case you'd end up with something like this:

    if (difficulty == 1)
    {
        cout << "Enter a word of your choice that contains no more than 5 characters\n";
        const int MAX_CHAR = 5;
        string wordEasy;

        for (cin >> wordEasy; wordEasy.empty() || wordEasy.size() > MAX_CHAR; cin >> wordEasy)
        {
            cout << "You entered a word that contains " << wordEasy.size()<< " characters.\n";
            cout << "Enter another word that contains 5 or less characters.\n";
        }
    }




write a programme that asks the user for lists of five name and write the names to a file rewind the file and display its content on the screen using the seekkg() and get()(function)

???????

Gonbe 32 Newbie Poster

You are modifying "t" more than once between two sequence points which results in undefined behaviour.

Gonbe 32 Newbie Poster

My objective is not to solve a sudoku.... It's to use the most basic bruteforcing algorithm to do the job..

I'm a little bit confused by this. Could you define what you mean by "the job" exactly? The algorithm you describe may result in a non-solvable sudoku while it could have been solved in it's original state. For example, consider something like this:

000|000|456
000|120|000
000|000|000
-----------
020|000|000
000|000|000
000|000|000
-----------
002|000|000
000|000|000
000|000|000

Am I right in thinking that your algorithm will place "1" at the top left square because it's the lowest value that can be there? (There is no 1 in the 3x3 square, none in the row and none in the column) But when you place a 1 there you result in a non-solvable soduko as there is no longer space for a '2' in the top row.

Gonbe 32 Newbie Poster

While there are multiple parts in your code that I find a bit shady, the real mess starts at the "check" and "fill" functions I guess. A very quick look at the fill function reveals this loop:

for(int p=0;p<9;)

In the other functions you used break statements to terminate the loop (which I think is poor in this case, one of the reasons being resulting in issues like this one), but here you don't.

Overall though I don't think you put much thought into your algorithm. I also think you're underestimating some things. For example, checking if a sudoku is valid might not be all that trivial. (Checking to see if a sudoku only has 1 unique solution for example might not be something you can quickly do. Although I'd have to ponder on it to say it with certainty..)

Aside from the algorithm you could divide your functions into smaller functions a lot better, and your naming could be a lot better too. multiple nested loops are not great to plough through.

You don't seem to have put a whole lot of effort into this, so I won't either, but a quick brainstorm on how I would approach this:

  1. Read a sudoku from a file (instead of letting it be entered by a user)
  2. Keep track of the remaining possibilities per empty square. (based on the row, column and 3x3 square the square is part of)
  3. Find the square which has the least remaining possibilities.
  4. Try these …
Gonbe 32 Newbie Poster

that is my current code. It seems to be working fine except that it keeps printing "your number is in index" twice...i don't understand why.

You're printing within your function and you are calling your function twice. Also you're assigning a boolean value to an integer (answer) which you're not even using.

-edit-
Minor cleanup of your function. More could be done, but atleast it's more readable now. I only did the things started in the summation at the top of the function; the rest is unaltered..

#include <iostream>
using namespace std;

bool binarySearch(int a[], int start, int end, int number)
{
    // 1. Removed the boolean 'b' as it was useless. (Validness of the range is now the condition for the loop)
    // 2. Instead of breaking out of the loop when the value is found, true is returned directly.
    // 3. Removed the start > end check inside the loop as it's redundant with the loop condition itself.
    // 4. Added a return false statement at the end of the function.
    int mid;

    while (start <= end)
    {
        mid= (start + end)/2;

        if (number == a[mid])
        {
            cout<< "The number you entered is located in index " << mid << ".\n";
            return true;
        }
        else if (number>a[mid])
        {
            start=mid+1;
        }
        else
        {
            end= mid-1;
        }
    }

    return false;
}

int main()
{
    // 1. Removed "answer" and anything associated.

    int a[]={5,10,23,34,45,55,66,78,81,98};
    int number;

    cout<< "Enter a number: "<<endl;
    cin>> number;

    if(!binarySearch(a,0,9,number))
        cout << "Your …
Gonbe 32 Newbie Poster

Adding to what's already said, here's a description from the specification (section 6.6.3):

A function returns to its caller by the return statement.

A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4). A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function. The expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy of a temporary object (12.2). Flowing off the end of a function is equivalent to areturnwith no value; this results in undefined behavior in a value-returning function.

A return statement with an expression of type “cvvoid” can be used only in functions with a return type of cvvoid; the expression is evaluated just before the function returns to its caller.

<cstdlib> also contains macro's you can use for returning from the program itself. Quote from the specification again (section 18.3):

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful terminationis returned. Otherwise the status returned is implementation-defined.

Note that this description is aimed at the function "exit" …

Gonbe 32 Newbie Poster

You're returning a bool, which can only be true or false. I'm not sure what your teacher wants, but it seems to me you only have to check whether or not a specified number is part of the array. (Or print the index from the function, but that seems like poor design) So something like this:

#include <iostream>

using namespace std;

bool BinarySearch(const int a[], const int start, const int end, const int number)
{
    if      (start >  end) return false;

    int middle = start + ((end - start) / 2);

    if      (a[middle] > number) return BinarySearch(a, start     , middle - 1, number);
    else if (a[middle] < number) return BinarySearch(a, middle + 1, end       , number);
    else                         return true;
}


int main()
{
    int a[] = {5, 10, 23, 34, 45, 55, 66, 78, 81, 98};
    int number(0);

    cout << "Enter a number: " << endl;
    cin >> number;

    if (BinarySearch(a, 0, 9,number))
        cout << "The array does contain the number " << number << endl;
    else
        cout << "The array does not contain the number " << number << endl;

    return 0;
}
Gonbe 32 Newbie Poster

You could use the fail/badbit state flags to see if there was an error. So something like this:

#include <iostream>
#include <limits>

using namespace std;

int main()
{
    int  number = 0;
    bool error  = false;

    do
    {
        cout << "[?] Enter a number: ";
        cin >> number;

        error = !cin;

        // Failbit or badbit is set.
        if (error)
            cout << "[!] Please enter a number.\n";

        // Note: The code clears the state flag and input buffer regardless. Depends a bit on what you think is
        // acceptable input. Something like "2323 12383" or even "123 hello" is accepted now, the remainder is just ignored.
        // It also treats numbers that are too big to fit into an int as erroneous input. It will also accept things like hexadecimal input.

        // Clear state flags.
        cin.clear();

        // Empty the input buffer.
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    while (error);

    return 0;
}
Gonbe 32 Newbie Poster

It's just to make things more flexible. (e.g. when you change the pattern to contain a different amount of elements, you don't have to update the size because it is derived. sizeof(grid_row) will return the size of grid_row in bytes. When you divide that by sizeof(int), which returns the size of a single integer in byte and is the type of the array, you get the amount of elements in grid_row. (e.g. if grid_row is 12 bytes, and an integer is 4 bytes then it will have 3 elements)

More is needed to make it fully flexible though, but this was just an easy fix so I just applied it when I saw it.

Gonbe 32 Newbie Poster

Quick lunch break experiment that doesn't use a two dimensional array. It's probably better to read with a 2D array though. Mainly done because it seemed fun, but posted it in case you find it useful..

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

const int AMOUNT_OF_RAILS = 3;
const int GROUP_WIDTH     = 5;

int  PyramidLineRows      (const int rowIndex);
int  PrintRail            (int rail, const string text, const int railcount, int groupRemainder, const int groupSize);
void PrintRailFenceSypher (string text, const int rails);


int PyramidLineRows(const int rowIndex)
{
    // The rail system consists of pyramids that alternate between inverted and non-inverted to form the zigzag-ing line.
    return (1 + (2 * rowIndex));
}


int PrintRail(int rail, const string text, const int railcount, int groupRemainder, const int groupSize)
{
    // We are starting inverted on anything but the last rail. Meaning visually the text is going downwards on the rail.
    bool isInverted = true;
    unsigned index      = rail;

    // The last rail is identical to the first rail aside from it's starting index.
    // Modify it's because it's index is used to calculate the row of the pyramid later on.
    if (rail == railcount - 1)
    {
        rail = 0;
    }

    // Go past the relevant character of the supplied string.
    while (index < text.length())
    {
        // It's time to print a new group.
        if (groupRemainder <= 0)
        {
            cout << " ";
            groupRemainder = groupSize;
        }

        // Print the character.
        cout << text[index];
        groupRemainder--;

        // The amount of places we have to …
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

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

"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

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

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

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

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

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".

Gonbe 32 Newbie Poster

Depends on how you want it to work. If you expect the formula as a single string you could do something like:

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

int main(int argc, char *argv[])
{
    int num1, num2, result;
    char op;
    int check=0;

    if (argc != 2)
    {
        printf("usage: %s <formula>", argv[0]);
    }
    else
    {
        sscanf(argv[1], " %d %c %d ", &num1, &op, &num2);

        if (op == 'q')
        {
            check = 1;
            return 0;
        }
        else
        {
            if  (op =='+')
            {
                result = num1+num2;
                printf("%d\n", result);
            }
            else if (op =='-')
            {
                result = num1-num2;
                printf("%d\n", result);
            }
            else if (op =='*')
            {
                result = num1*num2;
                printf("%d\n", result);
            }
            else if (op =='/')
            {
                result = num1/num2;
                printf("%d\n", result);
            }
        }
    }

    return 0;
}

example in- and output:

C:\>test 1+5
6

C:\>test "9 * 20"
180

C:\>test "    23  -        15      "
8

Another way is to see every formula element as a seperate command line parameter:

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

int main(int argc, char *argv[])
{
    int num1, num2, result;
    char op;
    int check=0;

    if (argc != 4)
    {
        printf("usage: %s <number> <operation> <number>", argv[0]);
    }
    else
    {
        sscanf(argv[1], "%d", &num1);
        sscanf(argv[2], "%c", &op);
        sscanf(argv[3], "%d", &num2);

        if (op == 'q')
        {
            check = 1;
            return 0;
        }
        else
        {
            if  (op =='+')
            {
                result = num1+num2;
                printf("%d\n", result);
            }
            else if (op =='-')
            {
                result = num1-num2;
                printf("%d\n", result);
            }
            else if (op =='*')
            {
                result = num1*num2;
                printf("%d\n", result);
            } …
Gonbe 32 Newbie Poster
  • Posting it all in "Code" because the forum keeps whining about invalid formatting, even though it's not..

    Hmm okay, starting from the start. I'd first recommend defining a couple of constants:

        // The amount of judges that will be judging.
        const unsigned int NUMBER_OF_JUDGES = 5;
    
        // The amount of competators.
        const unsigned int NUMBER_OF_COMPETATORS = 10;
    

    Next you'd have to identify what it is what you want your application to do. In this case you seem to want every judge judge every competator. This strongly suggests like repetition which means you'll likely want to use a loop construct. In pseudocode it'll look something like this:

    For every competitor:
    Ask every judge for a grade of this competator.
    Perform calculations based on the grades.

    This would translate to something like:

     // For every competator..
        for (unsigned int competator = 1; competator <= NUMBER_OF_COMPETATORS; competator++)
        {
            // Go past every judge..
            for (unsigned int judge = 1; judge <= NUMBER_OF_JUDGES; judge++)
            {
                // .. and ask it for a grade for the current competator
            }
    
            // Do "stuff" with the grades.
        }
    

    Next, before we start obtaining grades we'll need a place to store them at. There's a variety of tools for this, but for simplicity we'll be going for arrays. We can do this because the amount of grades required is known at compile-time. The code would change as follows:

    Next we'll have to ask a judge for …

Gonbe 32 Newbie Poster
char first[100], last[100];

Why use character arrays when you can use string objects? Change this to:

string first, last;


cin >> first, last;

Is incorrect. You're applying the comma operator here, which is why it compiles. The following will do what you're probably expecting:

cin >> first >> last;

You are using character arrays too for your functions. Also replace that with string objects. Note that you'll have to pass them by reference:

void lowercase(string& name)


int i = 1;

i is an index, but I assume you start at 1 on purpose because you want to keep the first letter's casing. In the function you do not check on the length of the string though. (e.g. what if the function somehow receives an empty string? The function could be applied general, in other projects)

toupper(name[0]);

You should assign the result of this to name[0] otherwise you're throwing it away.

if (name[0] == 'a' || name[0] == 'e' || name[0] == 'i' || name[0] == 'o' || name[0] == 'u')

You only check lower case with this. Aside it's a bit "meh".

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

The main reason why it's going wrong.. Why do you loop 100 times? It doesn't make sense. The body makes little sense too.

for (int i = 0; i < 100; i++)
        { 
            toupper(name[0]);
            name = name + name[i];
        } …
Lucaci Andrew commented: Quality post. +5
Gonbe 32 Newbie Poster

There's a bunch of things to be said about your code. Below is your code with some comments, I didn't change anything though.

#include <iostream>
#include <string.h> // C-header, iew!

using namespace std;

int main()
{
    // We're using C++, use a string object instead of a char array.
    char line[300];

    // I assume you specified the input as "xxx.xxx" and so on because you had issues
    // with spaces? For a C++ solution, look into the getline function from the string library:
    // http://www.cplusplus.com/reference/string/getline/
    cout<<"enter ascii code";
    cin>>line;

    int d = strlen(line);

    // I wouldn't increment 1 by 4 (given you'd fix the "i + 4" -> "i += 4" part), wouldn't "40" or whatever be valid, now you'd have to enter it as "040"?
    // Also watch out with the ending condition "d-1" should be d, although it does not 
    // matter due to the way you increment right now. But I can only imagine it is unintended.
    for(int i=0; i<d-1; i+4)
    {
        // This check isn't needed as you are already making assumptions about your input.
        // You're already assuming every ASCII value consists of 3 symbols and that there is
        // exactly 1 dot between them. You will always end up on a decimal. The idea to check
        // the input is good though! Just try to modify the loop condition first.
        if(line[i] != '.') 
        {
            // These statements are useless, they are also not very error proof depending on your input. (i+2) …
Gonbe 32 Newbie Poster

The term "pointer to arrays" could be somewhat misleading, depending on how you interpret it. Just as a heads-up: pointers and array aren't the same thing. One example that illustrates this:

#include <iostream>
using namespace std;

int main (void)
{
    const char* pointer = "Hello world!";
    const char  array[] = "Hello world!";

    // The address "pointer" is pointing to
    cout << "pointer:  " << (void*)pointer << endl; 

    // The address "pointer"'s value is stored at.
    cout << "&pointer: " << &pointer << endl;   

    // The memory address of the first element in "array".
    cout << "array:  " << (void*)array << endl;  

    // Also the memory address of the first element in "array"! There is no pointer stored in memory that points towards the array.
    // Could be confusing in a sense, as array == &array.
    cout << "&array: " << &array << endl;        

    return 0;
}
Gonbe 32 Newbie Poster

You're very close. You do have to pay better attention to the loop range however. Below is a fixed version of your code where I kept the changes minimal. The comments should speak for itself:

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

int main(void)
{
    int loop,count;
    char* string = "myname";    // The string you want to print.

    // 'loop' represents the amount of characters to omit. instead of 1-5
    // I made this 0 - (strlen(string) - 1).
    for(loop = 0; loop < strlen(string); loop = loop + 1 )
    {
        // 'count' represents the character of the string to print.
        // This should go from 0 till strlen(string) - 'loop' as we omit
        // the last 'loop' characters.
        for(count = 0; count < strlen(string) - loop; count = count+1)
        {
            printf("%c", string[count]);
        }

        printf("\n");
    }

    getch();
}
Gonbe 32 Newbie Poster

Note that a palindromes don't take punctuations and word dividers into account. For example:

Bush saw Sununu swash sub.

is a palindrome, although your application would say it's not. These types of problems are easy to think about recursively. The general idea would be that 'the first and last character should match' and the remains of the string should be a palindrome as well. You would end up with something like this:

#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; …
Gonbe 32 Newbie Poster

It wants an array of bytes and extracts a "length" value from that array by combining the bits in the second and third byte to form a 16 bit integer. (later stored in a 32 bit one..)

The most significant part of this 16-bit integer is formed by the third byte, the least significant section by the second byte.

edit:

example. Say you have this array as input, showing each byte as 8 bits.

[0000 0000][0101 0101][1111 0000]

The function would then produce a 16 bit integer like this:

[1111 0000 0101 0101]

This is stored into a 32-bit integer and then returned.

kmachstang commented: Perfect explaination +1
Gonbe 32 Newbie Poster

How about you first create a class representing a linked list that contains some basic operations?

  • Insert a value at a given index.
  • Remove a value at a given index.
  • Obtain the size
  • Get the value at a specified index ([] operator?)
  • Remove the first entry matching a supplied parameter.
  • Count the amount of occurrences of a supplied element.

and so on. You probably only need the first 4 anyway.

Gonbe 32 Newbie Poster

Hmmm... I think i'd start like this, just an idea though.

int main(void)
{
    return 0;
}