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

Errr oops, I somehow read 3b even though I ended up stating 3h in the reply.. I might take a look at 'h' when I have time to do so

Gonbe 32 Newbie Poster

For 3h you could do something like:

Time(const unsigned int hours , const unsigned int minutes , const unsigned int seconds)
        : hours(hours), minutes(minutes), seconds(seconds)
    {
        minutes += seconds / 60;
        seconds  = seconds % 60;

        hours += minutes / 60;
        minutes = minutes % 60;

        hours = hours % 24;
    }

As far as bubble sort goes, what is your problem with it? There's countless examples of bubblesort on the web and the algorithm itself is easy to comprehend. Maybe you should write a bubble sort function first that sorts an array of integers. After that you can easily modify it to sort an array of "Time" objects.

Gonbe 32 Newbie Poster

Cool! I was about to post this as a quick little example but good to hear you've managed to sort it out! I tried to keep it as much like the original as I could, although I ended up changing too much I guess. The steps are roughly the same atleast.

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

class Node
{
    public:
        Node(const char ch);
        Node(Node* const l, Node* const r);

        unsigned int get_frequency      () const;
        char         get_letter         () const;
        void         traverse           () const;
        void         increment_frequency();

    private:
        char    letter;
        unsigned int frequency;
        Node*   left;
        Node*   right;
};


void Node::increment_frequency()
{
    frequency++;
}

void Node::traverse() const
{
    // TODO: Provide some callback parameters that will be called for every node. Simple printf for now.

    // First traverse the left sub-tree, if present..
    if (left != NULL) left->traverse();

    // .. then print this node ..
    cout << "[Node] Letter: " << letter << ", frequency: " << frequency << ".\n";

    // .. and finally traverse the right sub-tree.
    if (right != NULL) right->traverse();
}

unsigned int Node::get_frequency() const
{
    return frequency;
}

char Node::get_letter() const
{
    return letter;
}

Node::Node(const char ch)
    : letter(ch), frequency(1), left(NULL), right(NULL)
{
}

Node::Node(Node* const l, Node* const r)
    : letter('*'), left(l), right(r)
{
    frequency = (l->get_frequency() + r->get_frequency());
}


void update_nodes(vector<Node*>& nodes, const char letter)
{
    for (unsigned int i = 0; i < nodes.size(); i++)
    {
        if (nodes[i]->get_letter() == letter)
        {
            nodes[i]->increment_frequency();
            return;
        }
    }
    nodes.push_back(new Node(letter));
}

bool …
Gonbe 32 Newbie Poster

At a quick first sight:

Replace

Player* players= new Player[No_Of_Players];

with

players= new Player[No_Of_Players];

Under that add:

No_Of_Players = No_Of_Players;

(Or: if you want to be more clear about the scope)

this->No_Of_Players = No_Of_Players;

Also make sure you set a string for "Name" in your constructors. Then your function should "work".
When using dynamic data you'll pretty much always want to define some overloads aswell, namely:

  • The copy constructor
  • The assignment operator
  • The destructor

It's probably worth it to look up. I'd probably use a vector (or something similar) here though instead of a dynamic array. You should also use the "string" object instead of using C-strings.

C++ also has something named a "member initialization list" you'd probably want to make a habit using. (look it up)

Gonbe 32 Newbie Poster

Now I am trying to figure how to actually implement it again.

I might be able to help there, it's however not clear to me what you're trying to do. Why is a single node in the tree the addition of two frequences? Would your tree only have 2 levels where the top level nodes have the combined frequency of their (2) childs? I'm not even sure if you would technically call that a tree. If you describe what you're trying to create I may provide an example.

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 tree making algorithm is fine

It is not fine. You should look into something called "scope". You're using "new" while it's not needed and you're saving pointers to objects that'll get out of scope when the function returns.

Gonbe 32 Newbie Poster

Quick and dirty proof of concept:

#include <stdio.h>

int sum(const unsigned int n)
{
    if (n == 0)
        return 0;
    else
        return n + sum(n - 1);
}


void print_sequence(const int n)
{
    int m       = 2,
        m_sum   = sum(m),
        k       = 0,
        r       = 0;

    while (m_sum <= n)
    {
        k = 0;
        r = n - m_sum;

        while (r >= k * m)
        {
            if (r == k * m)
            {
                while (m --> 0)
                    printf("%d ", (k++) + 1);

                return;
            }
            else
                k++;
        }
        m++;
        m_sum = sum(m);
    }
}


int main()
{
    int i = 0;

    for (i = 1; i <= 100; i++)
    {
        printf("%d = ", i);
        print_sequence(i);
        printf("\n");
    }
    return 0;
}

Based on this you'd develop a strong suspicion that any number except powers of 2 can be written this way. Might be fun to prove mathematically.

Gonbe 32 Newbie Poster

What exactly are the restraints on this task? I assume you can't use negative numbers, otherwise you could write any integer n as -(n - 1) + -(n - 2) + ... + 0 + ... + (n - 1) + n. You also mentioned the sequences can vary in length. I assume you're looking for lengths greater than 1? (Otherwise you could simply output a sequence of length 1 for every n) Is your program expected to output all possible sequences? (e.g. 30 = 6 + 7 + 8 + 9 but also 30 = 9 + 10 + 11)

The problem itself seems pretty interesting. I'd probably try to discover some sort of pattern. Looking at what numbers that can be generated using a sequence of length 1 or more you'd end up with a set of equations like:

3  + 2n
6  + 3n
10 + 4n
15 + 5n
...

These formula's could be generalized as sum(m) + mn. In this case we start atm = 2because we're not interested in sequences of length 1. If a given number x can be solved using of these formula's, you have the result. e.g: 30 = 10 + (4 * 5); you've found that n = 5 and m = 4. so the sequence you're looking for starts at (n + 1) and has length m. so: 5 + 6 + 7 + 8.

Looping over the possible equations and attempting to solve them should be easy (substract and modulo) aswell as checking when it's no use trying equations anymore because you'd never find a result.

Gonbe 32 Newbie Poster
O(f(n)+g(n)) = O(max(f(n),g(n)))? is it true ? 

Hmm been a while since I've done anything with Big O notation but I'll try anyway. No guarentees i'm right as your notation is somewhat unclear to me, especially the right hand side of the equation. Say f(n) > g(n), in this context I will assume you mean that from some n >= x0 the equation g(n) <= c * f(n) holds where c is a positive real. so g(n) ∈ O(f(n))

Continuing with f(n) > g(n) we'd want to show that O(f(n) + g(n)) ∈ O(f(n)) so we're looking for an x0 and c so that f(n) + g(n) <= c * f(n) we already know that a c2 exist for which g(n) <= c2* f(n) for some x0 so f(n) + g(n) <= c2* 2f(n) so if we pick c = 2 * c2 and x0 = 1 we're done. (analogous for g(n) > f(n))

O((fn)*(g(n)) = O(max(fn,gn)) ? can i say this thing ?

No. What if f(n) = n^2 and g(n) = n^(2), then the max is in O(n^2) but f(n)*g(n) is in O(n^4) and O(n^4) is not in O(n^2).

Gonbe 32 Newbie Poster

It isn't enitrely clear what sort of help you are looking for.

Read: extremely vague.

Gonbe 32 Newbie Poster

Maybe I wasn't clear, but the steps I posted earlier are also a brute-force approach to solving a sudoku.

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

Change ++= val; to val++;. (Or if you want harder to read code, remove ++= val; and change sum += val; to sum += val++;)

Gonbe 32 Newbie Poster
#include<iostream>

using namespace std;

int CountVowels (const string text)
{
    const string VOWELS = "aeiou";

    if (text.length() == 0)
    {
        return 0;
    }
    else
    {
        if (VOWELS.find(tolower(text[0])) != string::npos)
        {
            return CountVowels (text.substr(1)) + 1;
        }
        else
        {
            return CountVowels (text.substr(1));
        }
    }
}


int ArraySum (const int array[], const int size)
{
    if (size == 0)
    {
        return 0;
    }
    else
    {
        return array[0] + ArraySum(array + 1, size - 1);
    }
}


bool IsPalindrome (const string text)
{
    if (text.length() <= 1)
    {
        return true;
    }
    else if (!isalpha(text[0]))
    {
        return IsPalindrome(text.substr(1));
    }
    else if (!isalpha(text[text.length() - 1]))
    {
        return IsPalindrome(text.substr(0, text.length() - 1));
    }
    else
    {
        return (tolower(text[0]) == tolower(text[text.length() - 1])) && IsPalindrome(text.substr(1, text.length() - 2));
    }
}


void PrintBackwards (const string text)
{
    if (text.length() > 0)
    {
        cout << text[text.length() - 1];
        PrintBackwards(text.substr(0, text.length() - 1));
    }
}


int ReverseDigits (const int number, const int addition = 0)
{
    if (number < 10)
    {
        return (addition * 10) + (number % 10);
    }
    else
    {
        return ReverseDigits(number / 10, (addition * 10) + (number % 10));
    }
}


int Power (const int number, const int power)
{
    if (power <= 0)
    {
        return 1;
    }
    else
    {
        return number * Power(number, power - 1);
    }
}


int main()
{

    return 0;
}
Gonbe 32 Newbie Poster

-edit- no idea what you wanted "re" to return so it returns "nothing"..

#include<iostream>

using namespace std;

int re(int a)
{
    cout << a << endl;

    if (a > 0)
    {
        re(a - 1);
    }
}

int main()
{
     int a;

     cout<<"enter number\n";
     cin>>a;

     re(a);

     return 0;
}
Gonbe 32 Newbie Poster
#include <iostream>

using namespace std;

// 3x3 Matrix
const int MATRIX_SIZE = 3;

void SetElement (const int row, const int column, const int value, int matrix[][MATRIX_SIZE])
{
    // Only set the element if the supplied indexes are valid.
    if (row >= 0 && column >= 0 && row < MATRIX_SIZE && column < MATRIX_SIZE)
    {
        matrix[row][column] = value;
    }
}

void SetArea (const int row, const int column, const int value, int matrix[][MATRIX_SIZE])
{
    // Sets the element at [row][index] and all surrounding nodes except diagonal ones.
    SetElement(row    , column    , value, matrix);
    SetElement(row - 1, column    , value, matrix);
    SetElement(row + 1, column    , value, matrix);
    SetElement(row    , column - 1, value, matrix);
    SetElement(row    , column + 1, value, matrix);
}

int main()
{
    int matrix[MATRIX_SIZE][MATRIX_SIZE] = {{0,0,0},
                                            {0,0,0},
                                            {0,0,0}};

    // Example usage. First sets the 1,1 to 1 (and the corresponding area)
    // Then sets the 1,0 and 1,2 to 2.
    SetArea(1, 1, 1, matrix);
    SetArea(1, 0, 2, matrix);
    SetArea(1, 2, 2, matrix);

    // Print the matrix.
    for (int i = 0; i < MATRIX_SIZE; i++)
    {
        for (int j = 0; j < MATRIX_SIZE; j++)
        {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}
Gonbe 32 Newbie Poster
but in your opinion is it extremely inefficient,

That wasn't what I was saying. Your early versions contained things that resulted in behaviour that couldn't possibly be desired. In addition it contained things that served no purpose. (like the 'b' variable) I've edited my previous post to show how you can remove some stuff without really changing what the function does. I do think these are things you should try to look out for especially.

In this case you had to implement a specific type of searching algorithm meaning there's only so much you can do here performance-wise. (It'd be different if you had to develop any searching algorithm)

or does it really not matter since it gets the job done?

As a student I'd just go for something that "gets the job done" unless you've been given explicit performance requirements. But as a mentioned earlier, something that gets the job done should still be "proper"; it's no excuse for sloppy code. It is allowed to be less complicated at the cost of efficiency though. If I were you I'd focus on readable programs and at some point you could think about performance once you've got the hang of simple things.

e.g: Sorting alghorithms is something that is lectured at most institutions. If you need to sort something as part of a bigger assignment I'd go for something easy, like bubblesort for example. You'll one day find out it's quite horrible performance wise but as a …

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

I guess you have 3 options:
a) You return a bool and print the index from within the function.
b) You return a bool and return the index using a call-by-reference parameter.
c) You return the index if found, and otherwise -1. (Or whatever value that can't normally be returned)

I'd probably go for c normally. Here's a quick example of b:

#include <iostream>

using namespace std;

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

    index = start + ((end - start) / 2);

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

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

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

    if (BinarySearch(a, 0, 9, number, index))
        cout << "The array contains the number " << number << " at index " << index << ".\n";
    else
        cout << "The array does not contain the number " << number << ".\n";

    return 0;
}
Gonbe 32 Newbie Poster

It's a "habit" of mine. It's good practice to make things that should remain constant const for various reasons. You may omit it if it makes you more confident. You might also wonder why the middle is calculated in such a weird way. It's also something you may change back. It's something to prevent arithmetic overflow but it's not really required for this example I guess.

The reason I had rewrittne the function in the first place is because the function you created has some oddities in it which I think relate to one of your later questions. In my opinion you should think about it carefully and re-write it because in its current form its a bit of a mess. Generally I feel that I can get the point across easiest by commenting code line by line, I hope it convinces in this case too..

bool binarySearch(int a[], int start, int end, int number)
{
    int mid;        // Variable which will hold the index for the middle element.
    bool b=false;   // A flag indicating whether or not we should stop. (Name your variables better)

    // The index "start" has to be smaller or equal to "end", otherwise we're do not have to do anything (anymore).
    if(start<=end)
    {
        b=true;
    }

    // As long as the "keep-going" flag is true..
    while (b)
    {
        // Set the flag to false, unless proven otherwise in the remains of this iteration.
        // Note that this flag is useless right now as all options …
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

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

If you can't place the supplied code into the one you posted at the start I'm starting to doubt if you've written it yourself. What is unclear about he code(s) provided and what prevents you from changing your own to follow them?

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

I think you missed a part of your function on copy pasting. But your function seems alright except that it doesn't state base cases which results in it not always returning something. (although behaviour is undefined I think.. it might)

Anyway, something like this should fix it:

int power(const int base, const int exp)
{
    // Base case 1: base^0 = 1.
    // Even though you state positive integers as input, you might as well include 0 so you don't need a case for exp == 1.
    if (exp == 0)
    {
        return 1;
    }

    // Recursive case: base^n = base * base^(n-1)
    else
    {
        return base * power(base, exp - 1);
    }
}
Gonbe 32 Newbie Poster

Or just don't use recursion.

This is what I offered in my previous post. Understanding how it (recursion) works is still beneficial, even if you don't plan to use it.

I think that's the better choice for a linked list because the risk of stack overflow is greater when the recursive growth is linear or worse.

Given the stack size of most modern day compilers this will not realistically be an issue here. (but still "greater", I guess) I'm not sure what you mean by the recursive growth but I assume you mentioned the "or worse" part to word it for a general case.

Also, the iterative form of linked list appending isn't more complex:

This differs from person to person. While it hardly matters for a trivial function like this one I still find the recursive approach easier to comprehend.

There are a couple of things to note over the recursive implementation that aren't directly related to recursion:

I didn't take malloc allocation errors into account because I didn't want to complex the case more than needed. (even though a check for it is minimal. It might raise questions though) It's generally tricky to decide when to post something robust that is more complex or when to post something easy that is easy to break. Especially when you only have a single post to base on.

For strncpy(dst, src, count), count characters are always copied into dst.

Ah, this …

Gonbe 32 Newbie Poster

I think your problem lies within understanding recursion. Maybe you should look at simple recursion first to get a feel for it. For example:

#include <stdio.h>

// This function returns (n + amount) by using a recursive solution.
// For this example 'amount' must be >= 0.
int add(const int n, const int amount)
{
    // Base case: Adding 0 to n.
    if (amount == 0)
    {
        // This is ofcourse n itself!
        return n;
    }
    // Recursive case: Adding something bigger than 0 to n.
    else
    {
        // This is the same as 1 plus the result of adding n and amount - 1.
        return 1 + add(n, amount - 1);
    }
}

int main(void)
{
    printf("%d\n", add(20,34));
    return 0;
}

I could also create a non-recursive solution by the way if this works better for you.

Gonbe 32 Newbie Poster

Okay, clear. I'll start with explaining the idea of the function first. It's prototype is as follows:

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

We give it a linked list 'list' and data 'data' and the function will result in a new list which is the old list to which 'data' is added at the end.

I have implemented this as a recursive function meaning you express a problem using smaller cases of that problem and this continues until a simple base case is reached. The base case here is receiving an empty list. This means 'list' is NULL. So, we receive an empty list and data. Then what should we result in? We should then result in a list consisting of 1 node: the node that has 'data'. This is done in the following code:

    // The base case. We received an empty list to which we have to add a node.
    if (list == NULL)
    {
        // Allocate the new node.
        list = (node*) malloc (sizeof(node));

        // Set the fields of the node.
        list->next = NULL;
        strncpy(list->data, data, DATA_SIZE);
    }

The result it the address of this new node because this node is now the head of our list.

Then, the non-base case. This would be when we receive a list of size 1 or bigger. The question here would be: How can we reduce this to a smaller version of the problem? Well, a linked list is nothing more than a chain of …

Gonbe 32 Newbie Poster

I'm not realy sure what you mean and what code you are referring to. (I assume you are referring to the code where I replaced the "double pointer" with a return system) Are you asking of an explaination of how that code works, or are you looking for a way to modify the code as a whole to work differently?

Gonbe 32 Newbie Poster
    int counter = 30;

    // "While 'counter' is going to zero".
    while (counter --> 0)
    {
        // Do things on every decrement, if desired.
    }

=P

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

If I understand your question I don't see why you would want something like that. But a constructor is called when an object is created. So create a loop that iterates 37 times and create an M_48 object every iteration by calling the default constructor. (M_48 value;)

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

Using the the "%%" in the format string is the only good solution as far as I'm concerned. The function itself states that this should be used to print a single '%' symbol; it makes no sense to create all sorts of more complex constructs to do something that can be done in a simple manner.

Gonbe 32 Newbie Poster

What compiler did you use and did you change anything? When my code is run it should result in something like the following. (The bold sections are user-input)

Enter choice: 1
Enter the data. Type END if finished.
Hello
World
This is text spread
across multiple
lines!
END

Linked list contents:

  1. "Hello"
  2. "World"
  3. "This is text spread"
  4. "across multiple"
  5. "lines!"
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

There is indeed something wrong with your logic. I've fixed your code and added comments that show what the code is supposed to do. If anything is unclear after looking at it let me know:

#include <iostream>
#include <iomanip>

using namespace std;

// Note: If you don't know what 'const' is, just remove it or ignore it. It's just a habit of mine but isn't essential to the solution.
void Multitablefunc(const int n)
{
    // The first line that is to be printed shows the heading for the columns.
    // The first column is reserved because it will contains the row headers. So skip over that.
    cout << setw(5) << " ";

    // Then print the remaining numbers. This will simply be 1 till n.
    for (int column = 1; column <= n; column++)
    {
        cout << setw(5) << column;
    }
    // We're done with the headers, go to the new line.
    cout << endl;

    // We can now print the rest of the table.
    for(int row = 1; row <= n; row++)
    {
        // Every row starts with the row header, which is the number that is multiplied with.
        cout << setw(5) << row;

        // Then print the multiplication values, starting from the lowest.
        for(int column = 1; column <= n ; column++)
        {
            cout << setw(5) << row*column;
        }

        // We're done with this row go to the next line before printing the next row.
        cout << endl;
    }
}

int main()
{
    Multitablefunc(5);
    return 0;
}
Gonbe 32 Newbie Poster

It means list itself may not be changed, but we can change (*list). If it was a const node** then way may not modify (*list) because that would be const. (but we would then be allowed to change list because it's not longer const. Then we'd need const node** const)

Gonbe 32 Newbie Poster

Managed to get rid of the compiler errors. Compiles without warnings too.

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
    string name;

    cout << "What is the person's name?";
    cin >> name;
    cout << "Interesting! Thanks for letting me know. Don't forget to visit our cinema!\n";

    return 0;
}

You're welcome.

Gonbe 32 Newbie Poster

Just change frm 2 to 1,.nothing will happen either u want to put what number,bcoz in if else we state back the slot of aray that need to be check

I still don't get what you mean. There seems to be a bit of a language barrier as well. (no offense) I don't get what you're trying to say here. Maybe provide a short code example instead?

Gonbe 32 Newbie Poster

A cheesy way would be to brute force, you'd end up with something like this:

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

// The treshold mentioned in the exercise.
#define TRESHOLD (0.0001)

// Test number.
#define N (0.123456789)

int  max   (const int l, const int r);
bool solve (const double n, int* const a, int* const b, int* const c, int* const d);

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

bool solve (const double n, int* const a, int* const b, int* const c, int* const d)
{
    // Iterate over the possible 'a' values.
    for ((*a) = 24; (*a) <= 100; (*a)++)
    {
        // The check for 24 <= b <= 100 is implicit due to a's bounds.
        // Should make it explicit if you want the ranges as variables.
        for ((*b) = max(73 - (*a), 24); (*b) <= 121 - (*a); (*b)++)
        {
            // iterate over the possible 'c' values.
            for ((*c) = 24; (*c) <= 100; (*c)++)
            {
                // Same as for 'b' here.
                for ((*d) = max(90 - (*c), 24); (*d) <= 134 - (*c); (*d)++)
                {
                    // Found an answer. Should add a a treshold for accuracy due to floating points.
                    if (fabs(n - ((double)((*a) * (*c)) / ((*b) * (*d)))) <= TRESHOLD)
                    {
                        // Found the answer.
                        return true;
                    }
                }
            }
        }
    }

    return false;
}


int main()
{
    int a, b, c, d;

    // Will get rounded.
    printf("Trying to solve the equation …
deceptikon commented: Cheesy or not, giving away the answer is unhelpful -3
Gonbe 32 Newbie Poster
Also,when u declare char,u may declare like this char choice[2],then in the if else,u may do like this, if (choice[0]=='c') s0 the program will go check to that char

And then you would simply not use the second slot of the array? I can't think of any reason why you would want to do that. The only possible use of an array here would be an array consisting of valid commands matched to appropropriate functions by using function pointers. (Either by combining them in a struct or by using two arrays with linked indexes)

Also, semi-necro.

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 …