Gonbe 32 Newbie Poster
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <cctype>

using namespace std;

int main()
{
    /* Assumption: substring may overlap. E.g: "aaa" contains "aa" two times. */
    const string HAYSTACK = "abbaabbaabb";
    const string NEEDLE   = "abba";
    int counter = 0;

    /* A custom compare function for case-insensitive comparing */
    function<bool(const char, const char)> compare_fun = [](const char l, const char r) 
        { return toupper(l) == toupper(r); };

    string::const_iterator h_it(HAYSTACK.begin()), h_end(HAYSTACK.end());
    string::const_iterator n_it(NEEDLE  .begin()), n_end(NEEDLE  .end());

    h_it = search(h_it, h_end, n_it, n_end, compare_fun);

    while (h_it != h_end)
    {
        /* Perform tasks here, just a counter in this case */
        counter++;

        /* If assuming that substrings may not overlap, you'd do something like */
        /* advance(h_it, distance(n_it, n_end));                                */
        h_it = search(h_it + 1, h_end, n_it, n_end, compare_fun);
    }

    cout << "\"" << HAYSTACK << "\" contains \"" << NEEDLE << "\" " << counter << " times.\n";
    return 0;
}
Gonbe 32 Newbie Poster

p is an array of pointers. *(p+i) could be written as p[i] and *(p[i] + j) could likewise be written as p[i][j]. (So *(*(p+i)+j) could be written as p[i][j]) (and the contents of p are offsets off a which is 2-dimensional)

So you could write that printf as: printf("%d %d %d %d \n", p[i][j], p[j][i], p[i][j], p[j][i]);.

You could also declare the array a as static int a[4]={1,2,3,4};.

You could see
p[0] as {1, 2, 3, 4}
p[1] as {2, 3, 4}
p[2] as {3, 4}
p[3] as {4}

You loops request

p[0][0], p[0][0], p[0][0], p[0][0],
p[0][1], p[1][0], p[0][1], p[1][0],
p[1][0], p[0][1], p[1][0], p[0][1],
p[1][1], p[1][1], p[1][1], p[1][1]

which results in:

1, 1, 1, 1
2, 2, 2, 2
2, 2, 2, 2
3, 3, 3, 3
Gonbe 32 Newbie Poster

I'm not fully sure if I get what you mean with your example, but I think you might be looking for a map? If not, please be more clear about what you mean with list[i] and list[i_the_second].

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

Replace your printf with printf("%f %f",*p,*q);

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
By the way is there any reason that someone should use an iterator for this? Would it be more secure or fast?

The main benefit (as far as I know) is that the use of iterators makes your code generic because most (if not all) containers in the STL support it. Performance differences seem to vary, never really tested it myself.

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
If I pass a std::string to the function as pass by value, would it be considered as in-place modification if I don't create any new std::string in modifier function?

An algorithm is called "in-place" (or "in-situ") when it works on input using constant, small extra storage space. So yes, it would.

What is the standard and efficient method to modify std::string in place?

The standard would be to use its member functions: erase, insert, replace, swap, append, and so on. I wouldn't really know another way of dealing with std::string. As far as efficiency goes, you can't really say much about it I suppose. You use the member functions in an abstract way, you don't know how they work, you only know what they do.

How to change the end of std::string? One way that I could think of is to assign '\0' to all the trailing characters of the string but it would be inefficient to do so if length of string is large.

What exactly would your modification be? As mentioned before \0 wouldn't work for std::string. But if you had a C-string I don't see why you'd have to insert more than 1.

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

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

Do you mean something like this? (No idea if encryption is right. Just made whatever you did apply to the whole string)

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

// prime numbers
int p, q;
//compute
int n ;//= p * q;
//totient
int phi;// = (p - 1) * (q - 1);
int e; // not devider of phi;
int d;//= e mod phi;

int main()
{
    p = 3;
    q = 7;
    phi = (q - 1) * (p - 1);
    e = 69;
    d = (e % phi);
    n = p * q;
    long long c, dc, m;
    string msg, msg2, msg3;
    msg = "hallo";
    int i;

    cout << "Original line:\n";

    // Print the ASCII values of the message
    for(i = 0; i < msg.size(); i++)
    {
        // Show the character it is based on.
        cout<< static_cast<int>(msg[i]) << "(" << msg[i] << ") " ;
    }

    cout << "\nEncrypted line:\n";

    // Show the encrypted bytes
    for (i = 0; i < msg.size(); i++)
    {
        c = msg[i] ^ e % d;
        dc = c ^ d & n;
        cout << dc << "(" << static_cast<char>(dc) << ") ";
    }
}
Gonbe 32 Newbie Poster

TL;DR. Instead of posting the entire code post only the relevant part(s) or create a small example which reproduces the issue.

Gonbe 32 Newbie Poster

What are you using to do it right now? You can look into the sscanf function and/or the strtok function for this purpose. At a quick glance these will probably be sufficient and you don't have to create a custom solution. Can you post a minimal example of your split function so far? (only a the function itself and a call from main with representative input)

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

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

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

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

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

What is the type of DESTINATION?

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

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

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

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

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

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

There is no need for additional variables.

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

bool isVowel(const char symbol)
{
    return (string("aeiou").find(tolower(symbol)) != string::npos);
}

bool containsVowel(const string text)
{
    return ((text.length() > 0) && (isVowel(text[0]) || containsVowel(text.substr(1))));
}

int main()
{
    // Stuff with containsVowel..
    return 0;
}
Gonbe 32 Newbie Poster

Will your ID determine which of the two types the struct value is? Or do you have special guard values? I'd first consider if storing them like this is what you want. (You could use two containers) Do you need the type-specific values, or it is only the ID you're interested in?

If you actually need the values, maybe some sort of inheritance solution could prove useful. Maybe a union, like:

// No idea what your objects represent, so calling them Foo and Bar for now..
struct Foo
{
    double latitude;
    double longitude;
};

struct Bar
{
    int speed;
    int altitude;
};

union FooBar
{
    Foo foo;
    Bar bar;
};

struct Data
{
    int ID;
    FooBar foobar;
};

Also, this line confused me a little:

Go through the structure until I find the ID and then add the corresponding data to the structure

So you already known the ID's beforehand, but not the data? "If not found, create a new struct and add the ID." I assume this is always the case at the start right? You just continuously update the values belonging to ID's?

TL;DR: Need more information.

-edit-
Reading your post there are actually 3 types of objects, not 2. Are there more? (Or any mixtures of them?)
Also as memory usage probably isn't an issue it's maybe better to not use a union.

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
i have it started but not working correctly

How about you start with posting that?

-edit- And don't only post it, also state what you were trying to do and (if possible) where the code differs from your expectations.

Gonbe 32 Newbie Poster

As far as trimming goes, the following might be useful:

// Trim the start of a string.
string& TrimLeft(string& s)
{
    s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
    return s;
}


// Trim the end of a string.
string& TrimRight(string& s)
{
    s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end());
    return s;
}


// Trim the ends of a string.
string& Trim(string& s)
{
    return TrimLeft(TrimRight(s));
}
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

You could try something like this:

#include <iostream>
#include <sstream>
#include <limits>
#include <iomanip>

std::string double_to_string(const double value)
{
    std::ostringstream stream;

    // Go for maximum precision and take into account that converting could fail.
    if (!(stream << std::setprecision(std::numeric_limits<double>::digits10) << value))
    {
        // Possibly throw an exception instead.
        return std::string();
    }

    return stream.str();
}

int main()
{
    std::cout << "Char* array: " << double_to_string(12.345678).c_str() << std::endl;

    return 0;
}

If you use the boost libraries you could use "lexical_cast" too. You could also convert it C-Style using sscanf / sprintf. A little performance comparison that was provided on the boost website: http://www.boost.org/doc/libs/1_47_0/libs/conversion/lexical_cast.htm#performance

Gonbe 32 Newbie Poster

let me know if anyone has any pointers thankS!

0x0F021016
0x0E031418
0x08051033

Ba dum tss

any help would be greatly appreciated!!! thanks!

Anyway, at a quick first glance I don't really see anything that could cause errors. What have you established yourself already? At what point do problems arise?

-edit-

Actually, replace

cout<<grid[x,y];

with

cout<<grid[x][y];
Gonbe 32 Newbie Poster

It's more of a hint/possible solution towards what you need. As mentioned in the post it's something I quickly wrote down to show the idea of using a string you manipulate. It should work for an arbitrary bit count though, although I'm sure performance-wise it could be improved on.

You may use it, sure, but if you don't understand what's going on I don't see much of a point. I'll let you decide what you think is best for yourself.

-edit-

gonbe i tried to modify ur code for my problem but could't achieve, what i wanted

You should only have to change the define from 6 to 48. If that doesn't result in what you want I don't think I understand your problem correctly. If you set 48 it will take forever to finish, but that is to be expected with 2^48 strings that have to be calculated and printed. The logic of it should work. I'm not sure if I have time tomorrow to try to fix your existing code, it will probably be monday at the earliest if at any time. Try to figure out in the meanwhile what's going wrong and post your attempt(s). The bits increase, but that doesn't matter too much for the application's logic.

HunainHafeez commented: gonbe i tried to modify ur code for my problem but could't achieve, what i wanted, so if you can possibly make any changes within my code to make it work for 48 bits then please resolve it, i wasted a whole lot of time on it, Help would be appreciated de +0
Gonbe 32 Newbie Poster

Such C++ includes in C code. The way you do it will become problematic when using 48 bits as the amount of possible permutations is huge. You don't have to store them though and just output them as they get calculated. Another thing that might become an issue is the use of counters (depending on how you do it). You could use an unsigned long long which is guaranteed to be 64 bits but it's a C99 standard feature. I'd go for re-writing the alghorithm though.

Depending on what your goal is exactly you could use a string. A quick attempt using a recursive method would result in something like this:

#include <stdio.h>

#define BIT_COUNT (6)

void print_bits(int bitcount, char* bitstring, int offset)
{
    if (bitcount == 0)
    {
        printf("%s\n", bitstring);
    }
    else
    {
        bitstring[offset] = '0';
        print_bits(bitcount - 1, bitstring, offset + 1);

        bitstring[offset] = '1';
        print_bits(bitcount - 1, bitstring, offset + 1);
    }
}

int main()
{
    char bits[BIT_COUNT + 1];
    bits[BIT_COUNT] = '\0';

    print_bits(BIT_COUNT, bits, 0);

    return 0;
}
Gonbe 32 Newbie Poster

You can't say anything useful about the code, only that it results in undefined behaviour; you're writing to the same variable twice or more without an intervening sequence point.

See section J2 and section 6.5 here.

-edit-

Looked up the exact point in section J2 I wanted to refer to:

Between two sequence points, an object is modified more than once, or is modified
and the prior value is read other than to determine the value to be stored (6.5).

Then, from section 6.5 (expressions):

Between the previous and next sequence point an object shall have its stored value
modified at most once by the evaluation of an expression. Furthermore, the prior value
shall be read only to determine the value to be stored.

Then from Annex C one of the definitions of a sequence point:

The end of a full expression: an initializer (6.7.8); the expression in an expression
statement (6.8.3); the controlling expression of a selection statement (if or switch)
(6.8.4); the controlling expression of a while or do statement (6.8.5); each of the
expressions of a for statement (6.8.5.3); the expression in a return statement
(6.8.6.4).

Gonbe 32 Newbie Poster

This should work:

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

struct CALL_DATA
{
    string list;
    int number;
    int lcmonth;
    int lcyear;
};

int main()
{
    int i = 0;
    CALL_DATA listd[100];

    ifstream file ("list.txt");

    if (file.is_open())
    {
        while (file.good())
        {
            char temp = 0;

            getline(file, listd[i].list);

            // The file could have ended with a newline symbol meaning the last line was empty.
            // I didn't knew how you created your file so I added this check. You can remove it if needed.
            if (listd[i].list.length() != 0)
            {
                file >> listd[i].number;
                file >> listd[i].lcmonth;
                file >> listd[i].lcyear;

                while (file.get() != '\n' && file);

                cout << "List: " << listd[i].list
                     << "\n\tnumber:  "  << listd[i].number
                     << "\n\tlcmonth: " << listd[i].lcmonth
                     << "\n\tlcyear:  "  << listd[i].lcyear
                     << endl << endl;

                i++;
            }
        }
        file.close();
    }

    cout << "Amount of entries read: " << i << endl;

    return 0;
}
Gonbe 32 Newbie Poster

While I don't necessarily agree with creating a function to compare integers his suggestion is that you have a string-like compare. You get two numbers and if the first is smaller than the second the function returns -1, if they are equal it returns 0 and otherwise it returns 1.

I wouldn't create a function for that personally though as it doesn't really add anything in my opinion. You're not adding the result to something directly so you'd still have to branch on it's result. I'd go for creating functions of which you can convince yourself it makes sense to have them as functions in the first place and/or because it can be identified as an individual process in the entire application's workings.

Gonbe 32 Newbie Poster

You commented your code with some steps. You could say your program does the following:

  1. Intialize random seed.
  2. Generate secret number.
  3. Play guessing game. (keeps starting guess attempts until guessed, tracks amount of tries)
  4. Do guess attempt. (either right or wrong, involves asking the user for a number)
  5. Obtain number from user.

You might be able to find more subtasks or create a different list but the aim is to find subtasks and place their logic in seperate functions that call eachother.