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

You could "outsource" validation. If your regex is working, you could use match_results to obtain the different section, create a tim structure and pass that to mktime() for validation.

Gonbe 32 Newbie Poster

Muh.

first, askk for the initial balance of the bank accounts

So what have you tried, and what isn't working as expected? If you haven't gotten to the point of coding yet, what part of the design is it you cannot develop?

reject negative balance

So what have you tried, and what isn't working as expected? If you haven't gotten to the point of coding yet, what part of the design is it you cannot develop?

 then as for the transaction ; option are deposit, withdraw, and transfer

So what have you tried, and what isn't working as expected? If you haven't gotten to the point of coding yet, what part of the design is it you cannot develop?

then ask for the account ; options are checking and saving

So what have you tried, and what isn't working as expected? If you haven't gotten to the point of coding yet, what part of the design is it you cannot develop?

 then ask for the amounts ; reject transaction that overdraw an accounts.

So what have you tried, and what isn't working as expected? If you haven't gotten to the point of coding yet, what part of the design is it you cannot develop?

 at the end,print balances of both accounts. 

So what have you tried, and what isn't working as expected? If you haven't gotten to the point of coding yet, what part of …

Gonbe 32 Newbie Poster

I don't really understand what you're trying to say, but can the arrays be modified? Or must their content remain in-place? If the first I'd probably sort and compare if based on that. Something like this: (something quickly made, not tested)

#include <iostream>
#include <algorithm>

using namespace std;

bool SortedIsPartOf(int first[], const int firstSize, int second[], const int secondSize)
{
    // An empty array is part of any array.
    if (firstSize == 0)
        return true;

     // Something bigger can't be part of something smaller.
    else if (firstSize > secondSize)
        return false;

    else if (first[0] == second[0])
        return SortedIsPartOf(first + 1, firstSize - 1, second + 1, secondSize - 1);

    else
        return SortedIsPartOf(first, firstSize, second + 1, secondSize - 1);
}

// Determine if "first" is part of "second".
bool IsPartOf(int first[], const int firstSize, int second[], const int secondSize)
{
    // Sort both arrays
    sort(first, first + firstSize);
    sort(second, second + secondSize);

    return SortedIsPartOf(first, firstSize, second, secondSize);
}

int main()
{
    // When is a array a part of another one? From a math point of view {3, 3} equals {3} but here I assume the first is not a part of the second.
    int data[]  = { 8, 2, 5, 6, 2, 9, 1 };
    int data2[] = { 5, 8 };

    cout << IsPartOf(data2, sizeof(data2) / sizeof(int), data, sizeof(data) / sizeof(int));

    return 0;
}
Gonbe 32 Newbie Poster
ASAP PLS..TENKS

WOOF! NO PRAPLEM.

#include <iostream>
#include <cctype>
#include <algorithm>

using namespace std;

int main()
{
    string answer;

    do
    {
        cout << "Enter \"y\" or \"n\": ";
        getline(cin, answer);

        // Trim whitespaces before/after input. We tolerate those.
        answer.erase(find_if(answer.rbegin(), answer.rend(), not1(ptr_fun<int, int>(isspace))).base(), answer.end());
        answer.erase(answer.begin(), find_if(answer.begin(), answer.end(), not1(ptr_fun<int, int>(isspace))));

        if (answer.size() > 0)
        {
            // Convert the entered character to lowercase.
            answer[0] = tolower(answer[0]);

            // Allow whitespaces after our input, but nothing else.
            if ((answer[0] != 'y' && answer[0] != 'n') || answer.size() > 1)
            {
                cerr << "Invalid input!\n";
            }
        }
        else
        {
            cerr << "Please provide input!\n";
        }
    }
    while (answer.size() == 0 || answer[0] != 'y');

    return 0;
}

-edit-

Oh oops, post looks silly after that reply I guess. Mods/admins may remove the code/post if needed.

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

I'm just bored. Besides, on a topic this common implementations can be found all-over anyway; if he wants code to copy he can/will get it. I always assume people don't mindlessly copy-paste things. If they do, it's their choice and it'll bite them in the ass at some point. The code present in the beginners guide ancient dragon linked could be copied as well.

-edit-
As this is subject I've seen multiple times in a short timespan, maybe I should improve and extend the above example and post it as a code snippet or whatever? (Maybe a C version would be more useful)

Gonbe 32 Newbie Poster

Quick example: (can be infinitely improved, but "meh")

#include <iostream>
#include <stdexcept>

using namespace std;

struct ListItem
{
    int value;
    ListItem* next;
};

typedef ListItem* pListItem;

// Should use templates.
// Just used as a shell for some operators, if you need the logic look at the private member functions.
class LinkedList
{
    public:
        // Constructors.
        LinkedList();

        // Member functions.
        void PushBack (const int value);
        void Remove   (const int value);
        int  Size     () const;

        // Member operators.
        int&       operator[] (const int index);
        const int& operator[] (const int index) const;

        // Friend functions.
        friend ostream& operator<< (ostream& stream, const LinkedList list);

    private:

        // Private member functions.
        void Add    (pListItem& list, const int value);
        void Remove (pListItem& list, const int value, const pListItem previous);
        int& At     (const pListItem list, const int index) const;
        int  Size   (const pListItem list) const;

        // Private member variables
        pListItem head;
};


LinkedList::LinkedList() : head(NULL)
{
}


void LinkedList::Add(pListItem& list, const int value)
{
    // Empty list!
    if (list == NULL)
    {
        // Create the item.
        list = new ListItem;

        // Set the values.
        list->next  = NULL;
        list->value = value;
    }
    else
    {
        Add(list->next, value);
    }
}


void LinkedList::PushBack(const int value)
{
    Add(head, value);
}


void LinkedList::Remove(const int value)
{
    Remove(head, value, NULL);
}


int LinkedList::Size() const
{
    return Size(head);
}


ostream& operator<< (ostream& stream, const LinkedList list)
{
    stream << "[";
    for (pListItem current = list.head; current != NULL; current = current->next)
    {
        if (current != list.head)
        {
            stream << ",";
        }

        stream << current->value;
    } …
Gonbe 32 Newbie Poster

You know that a linked list is basically a value and a pointer to the next element in the list. (if any) So somewhere you define what the starting point of your linked list is. (the head) With that you can access every element in the list by using the pointers. Adding data is relatively easy too, because you work with pointers. Say you have a list containing "2->10" and you want to add "5" in the middle. Then you're have to let the pointer of "2" point to "5" and the pointer of "5" point to "10" so you get 2->5->10. Removing data is similar. It's all pretty simple, you just need to code the functions.

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

You didn't quite understand the substring member function. There might also be something wrong with your overall design/logic. But maybe you should describe it in words. It could be it does make sense but you just didn't manage to translate it correctly to code. Here's your code with some comments and some modification:

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

void conversion(string name);
void lowercase(string& n);

int main()
{
    string first, last;
    char answer;
    do
    {
        cout << "Enter a name (first then last): ";

        // Still wrong.. replaced.
        //cin >> first, last;
        cin >> first >> last;

        lowercase(first);
        lowercase(last);

        conversion(first);
        conversion(last);

        cout << "\nWould you like to convert another name? (y/n) ";
        cin >> answer;
    }
    while (answer == 'Y' || answer == 'y');

    return 0;
}

void conversion(string name)
{
    // none needed.
    //string way, ay, consonants;

    if (name[0] == 'a' || name[0] == 'e' || name[0] == 'i' || name[0] == 'o' || name[0] == 'u')
    {
        // This statement will do "nothing", removed.
        //toupper(name[0]);

        // 'way' is uninitialized. Either use the desired value directly or initialize way accordingly. I did the first below.
        //name = name + way;

        name = name + "way ";
        cout << name;
    }
    else
    {
        cout << name.substr(1) << name[0] << "ay ";
        // You don't really need to go past every character, removed
        /*
        for (int i = 1; i < (int)name.length(); i++)
        {
            // I don't know what you're trying to do here. It doesn't matter what the other characters …
Gonbe 32 Newbie Poster
printf("\nFile Will Not Open!!!!\n);

You are missing a terminating quotation mark. Also I would be very scared if an application would respond to me using so many exclamation marks, but this is not technically an error.

printf(\navg is beint calculated!!!");

You are missing the opening quotation mark.

Void open(void);

"Void" is not a valid type. Use "void".

Your opening and closing of functions is a mess. Use parenthesis properly.. The following functions need to be fixed: "open", "read" and "average".

float average(float *number,int non)

This is the function header for the "average" function, but it is declared as:

float average(float*);

They should match.

void write(float *number,float,ave,int non)

There's a comma between "float" and "ave" that doesn't belong there.

Your "write" function has the following header (after a previous fix):

void write(float *number,float ave,int non)

But it is declared as

void write(float*,float);

They should match.

fptrin=fopen("avg.dat""r");

You're missing a comma between the two strings.

fprintf(fptrout,"%f\n",number[i];
        printf("\n%f",number[i]

These are missing the ')' symbol and the last also misses the semicolon.

In your "read" function:

for(i=0;i<non;i++)

"non" does not exist in that function. I don't really want to look into the logic of your application right now so I've just added a 'non' parameter to it, like the other functions.

done=fscanf(fptrin,"%f",&number[i];

You are missing the closing ')' symbol again.

for(i=o;i<non;i=i++)

Both i and o are undeclared in …

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

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

have any ways to solution this problem? please help me get some idea.Now i dont have any good ideal for this problem.

How about you read the replies? There is no solution to your problem because it's not possible to do what you want. Add another argument to "func" that contains the size of the buffer pointer to by "ptr".

Gonbe 32 Newbie Poster

I'm pretty sure the std::string overload was added in C++0x. I can only imagine they didn't add it earlier o prevent a dependancy between the <string> and <fstream>. I haven't been able to find an official statement about why they made the choice to add it in C++0x, although I'm sure it somewhere..

Section 27.9.1.4 of a 2010 draft of the C++0x standard (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf) contains the function declaration.

Gonbe 32 Newbie Poster

i want a simple code using simple c functions i'm just learning c so in simple code is it possible

The code I posted is almost identical to the one you posted yourself. That should be simple for you, unless you copy pasted the code in your starting post and didn't have a clue about it in the first place.

Gonbe 32 Newbie Poster

Your GCD function will divide by zero when you enter 0 as its second argument. You can also supply negative numbers. You're lacking return types as well.. I assume that you don't feel the need to check your arguments as you have full control over them. You should still assert them in case it somehow does happen. Applying those things result in:

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

int gcd(int,int);
int lcm(const int, const int);

int main(void)
{
    int a, b;

    printf("Enter the values for a and b:\n");
    scanf("%d %d", &a, &b);

    printf("gcd is %d.\nlcm is %d.\n", gcd(a,b), lcm(a,b));

    return 0;
}

int gcd (int c, int d)
{
    assert(c > 0 && d > 0);

    int r;

    do
    {
        r = c % d;
        c = d;
        d = r;
    }
    while(r != 0);

    return c;
}


int lcm (const int a, const int b)
{
    assert(a > 0 && b > 0);

    return (a * b) / gcd(a, b);
}

please send me code asap

I deliberately went to get a coffee before posting on the reply button because of this while I don't even like coffee.

Finally, the GCD is one of those classic algorithms you generally come across when learning about recursive functions. Those functions use the algorithm of Euclides, you can read more of that here: http://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm

Gonbe 32 Newbie Poster

Yes this works but I have been asked as a task to do:

That task just makes no sense.

To get this straight, you've been given this piece of code:

New(Shoe[num], num);

And you're supposed to make that work in a way that it adds a new element to your Shoe variable, which is an array of "Shoes" objects. (Note that this is already confusing)

In order to do that your function would need to have the following type:

void New (Shoes& Shoe, int& num)

Then you could use the implementation you had previously:

cout << "Enter Name, Number and Date: ";
cin >> Shoe[num].Name >> Shoe[num].Number >> Shoe[num].Size;
num++;

You would really have to watch out how you call the function though. if 'num' is equal to or larger than "Shoe"'s capacity you'll be writting on memory that's out of bounds.

If you're allowed to modify the function you should at least add another parameter that states the capacity of the buffer so you can compare that with 'num'.

Gonbe 32 Newbie Poster

You are applying "&" to an array variable. This works differently from pointers. It gives the memory address to the first element, so basically it can be considered int*. (cast to) Something like this will work as you'd expect it to:

#include <stdio.h>

int main (void)
{
    unsigned int i = 0;

    int array[] = {1,2,3};

    int *arrayAddr = (int*)&array;  // ArrayAddr is a pointer to the first element in "array".
    int **pArray   = &arrayAddr;    // pArray is a pointer to ArrayAddr.

    (*pArray)[1] = 99;              // Dereferencing "pArray" gives us "arrayAddr", [1] gives us *(arrayAddr + 1).

    // Show the new contents of "array".
    printf("Array: ");

    for (i = 0; i < sizeof(array) / sizeof(int); i++)
    {
        printf("%d ", array[i]);
    }

    return 0;
}

More about the differences between pointer types and array types (and this issue in particular) can be found here: https://blogs.oracle.com/ksplice/entry/the_ksplice_pointer_challenge

Gonbe 32 Newbie Poster

I don't quite understand it still, could you explain why something like the following is wrong?

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

using namespace std;

int main()
{
    // Using an array for initialization, not needed in C++0x.
    string names[] = {"Malik", "Maliq", "Malique", "Mallick", "Malick", "Malicq", "Malik"};
    vector<string> data (names, names + sizeof(names) / sizeof(string));

    // Sort the data first in an attempt to make things more efficient. I'm assuming the alghoritm one
    // is efficient, but you could replace this with your own version.
    sort(data.begin(), data.end());

    // Count the highest occurrence.
    string standardName, previousName;
    int highestOccurrence = 0, currentOccurrence = 1;

    for (vector<string>::iterator it = data.begin(); it < data.end(); it++)
    {
        if ((*it) == previousName)
        {
            currentOccurrence++;
        }
        else
        {
            if (currentOccurrence > highestOccurrence)
            {
                highestOccurrence = currentOccurrence;
                standardName      = previousName;
            }

            currentOccurrence = 1;
            previousName      = (*it);
        }
    }

    cout << "The highest occurrence is: " << standardName << " (" << highestOccurrence << ").\n";

    // Replace all entries in the vector with the new standard.
    fill (data.begin(), data.end(), standardName);

    return 0;
}
Gonbe 32 Newbie Poster

I got that much. But how is your data stored now? Can we assume that the input for this problem always contain only names that are similar to eachother, or do we first have to group them somehow? If the latter is the case I wouldn't quite sure what your rules are for this.

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

I don't really get what you're trying to describe. What do you mean by "the probability of Malik"? The probability of what?

From what you're describing it seems to me that you just want to count how many times every name occurs, pick the one with the highest occurrence (question: What would you say is desired if two names appear equally as much?) and replace all others with that one.

More importantly, how is your data stored? I assume your data set contains more than just "Malik" and variations of it. If so, how are you going to determine which names are similar to eachother? To illustrate this with an example similar to yours, what if your population looked like:

Malik, Maliq, Malique, Mallick, Malick, Malicq, Malik, ChuckNorris, ChuckNorris, ChuckNorris

ChuckNorris has the highest occurrence here, but given your description you don't want that one becoming the standard for "the Maliks", right? So please provide more information about your data set and assumptions that may be made about it.

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

Haha, I love how you thank deceptikon for his advice to "do anything" as if it's something you hadn't considered previously. Good luck!

Gonbe 32 Newbie Poster

Yes, but they have nothing to do with long lines. ;)

They do in the context I posted that in; you cannot guarantee that a comment found within read data ends within that same data.

Actually, this is a good place for an extended fgets() that isn't restricted by a buffer size:

Yeah, that's probably useful.

As far as edge cases go, I'd be more worried about true edge cases for comments. Two that come to mind are // in places where they don't start a comment (such as inside a string) and line continuation. Though I suspect the OP's project doesn't need to be absolutely thorough in terms of all possible cases.

Adding that would introduce quite some complexity yes. I also don't think it's what the OP wants though, given his minimalistic description of his problem (When interpreted more freely his title may imply him wanting to remove comment blocks too (with this I mean "/* */" ) even though he only mentions a subset of what comments could be in the part added in parenthesis).

Gonbe 32 Newbie Poster

There's some edge cases that could make it somewhat complex. Mostly because you could have lines bigger than your buffer. This will result in two types of reads: those that end in newlines, and those that do not. (and a newline happens to be exactly the symbol that marks the end of the section you want to ignore) You'll need to keep track of whether you're inside a comment or not. In addition you could have reads like "<text>/" followed by a next read that looks like "/<text>". You need to detect that too.

Below is a little example. A little sloppy due to time constraints but it shows the concept I think.

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

#define BUFFER_SIZE (80)

int main(void)
{
    FILE *fp  = NULL,
         *fp1 = NULL;
    char *token_pos = NULL,
         *copy_pos  = NULL;
    const char *fname  = "a1.txt",
               *fname1 = "a2.txt";
    char str[BUFFER_SIZE] = {0},
         character        = 0;
    int buffer_length     = 0;
    bool inComment        = false;


    // Open the files.
    fp  = fopen(fname ,"r");

    // Opening of the input file failed.
    if(fp == NULL)
    {
        printf("Error on opening input file \"%s\".\n", fname);
    }
    else
    {
        fp1 = fopen(fname1,"w");

        // Opening of the output file failed.
        if (fp1 == NULL)
        {
            printf("Error on opening output file \"%s\".\n", fname1);
        }
        else
        {
            // Note that feof becomes true after attempting to read out of bounds.
            // An easier way is probably to use fgets as your loop condition.
            while (fgets(str, BUFFER_SIZE, fp) != NULL)
            { …
Gonbe 32 Newbie Poster

Just a little heads-up: That string should ofcourse be declared as a "const char" and not a "char". Sorry for providing a bad practice.

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

Your code doesn't take leap year into account, and "magic numbers" are generally a bad idea. (Although they are unlikely to change in this case..)

You could try something like this:

#include <iostream>
#include <cassert>

using namespace std;

enum Month { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
const int DAYS_PER_MONTH[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };


bool IsLeapYear (const int year)
{
    assert(year >= 0);

    // See: http://en.wikipedia.org/wiki/Leap_year
    return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0));
}


// Obtain the daynumber of the first day of a given month in a given year.
int GetFirstDay(const Month month, const int year)
{
    assert (year >= 0);
    int result = 1;

    for (int currentMonth = Jan; currentMonth < month; currentMonth++)
    {
        // Add 1 day for february when the supplied year is a leap year.
        result += DAYS_PER_MONTH[currentMonth] + (currentMonth == Feb && IsLeapYear(year));
    }

    return result;
}


// Obtain the amount of days in a year.
int DaysInYear (const int year)
{
    assert (year >= 0);
    return GetFirstDay(Dec, year) + DAYS_PER_MONTH[Dec] - 1;
}


// Your function.
void SplitDate(const int dayOfYear, const int year, int *month, int *day)
{
    assert (dayOfYear >= 1 && dayOfYear <= DaysInYear(year) && year >= 0 && month != NULL && day != NULL);

    // Set the month
    for (*month = Jan; *month < Dec && GetFirstDay(static_cast<Month>(*month …
Gonbe 32 Newbie Poster

That said, some comments on the code:

char*s1="Testing the function ";
char*s2="Testing str_cat";

While declared char*, note that they point to const char*. This means you won't be able to modify them. Declare them as follows instead:

char s1[] = "Testing the function ";
char s2[] = "Testing str_cat";

Then your copy function:

int str_copy( char *  &dest,  char *  src)
{
    int len=0;
    while(src[len])
    {
        dest=src;
        len++;
    }
    return len;
}

There is no need for a reference here, your method of copying is faulty too. You're assigning the pointers itself all the time. Change it to something like this:

// You should give the sizes of the arrays too.
// What will you do now when 'dest' is smaller than 'src'?
// I didn't fix that for you in the version below.
int str_copy(char* dest,  char* src)
{
    int len = 0;

    while(src[len])
    {
        dest[len] = src[len];
        len++;
    }

    // The loop stops at '\0' so have to append that seperately.
    dest[len] = '\0';

    return len;
}

Note I only fixed what was wrong in your code. The function itself is still very error-proof because you don't check the bounds of the arrays.

Then your concatenate function:

int len=0;
    while(dest=src1=src2)
    {
        dest++;
        src1++;
        src2++;
        len++;
    }
    return len;

Well, this code just doesn't make sense. Your condition in the while statement will pretty much always be true, and in the loops body you don't assign anything you just …

Gonbe 32 Newbie Poster

C-string don't automatically grow. You have to be aware of the array's dimensions. Why don't you use 'string' objects instead as we're talking about C++ here?

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

I find your code pretty difficult to read. Why don't you divide problems into a smaller problems by using functions? I don't really know the theory behind perfect numbers that well but on a quick attempt I would go for something like this, which is quite different and (in my opinion) easier to read.

Note that the m-superperfect number section is probably incorrect. This place mentioned some results for any k so I just included it.. I might look into it at some point (especially optimalization might be fun, though some are obvious and easy) but for now the point I'm trying to make it that you should structure your code better.

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

#define UPPER_BOUNDARY (10000)
#define MAXIMUM_K      (6)
#define MAXIMUM_M      (3)

struct List
{
    int value;
    struct List* next;
};

// Functions to manipulate the list structure.
static void AddToList  (struct List** list, const int value);
static void RemoveList (struct List** list);

// Internal helper functions.
static struct List* GetDivisors     (const int n);
static int          Pow             (const int n, const int k);
static int          DivisorFunction (const int n, const int k);

// The functions you will need. (would be in the header normally)
bool IsPerfect      (const int n);
bool IsSuperPerfect (const int n);
bool IsMultiPerfect (const int n, const int k);
bool IsMSuperPerfect(const int n, const int m);
bool IsMKPerfect    (const int n, int m, const int k);


static void AddToList(struct List** list, const int value)
{
    assert (list …
Gonbe 32 Newbie Poster
#include <iostream>
#include <cassert>

using namespace std;


void Repeat      (const char symbol, const int amount);
int  RowToWidth  (const int row);
int  ObtainHeight();


int ObtainHeight()
{
    int height(0);

    do
    {
        if (cin.fail())
        {
            cerr << "Invalid input.\n";

            cin.clear();
            while (cin.get() != '\n');
        }

        cout << "Enter the height of the pyramid: ";
        cin  >> height;
    }
    while (cin.fail());

    assert(height >= 0);

    return height;
}


void Repeat (const char symbol, const int amount)
{
    assert(amount >= 0);

    for (int i = 0; i < amount; i++)
    {
        cout << symbol;
    }
}


int RowToWidth (const int row)
{
    assert(row >= 1);
    return(row * 2 - 1);
}


int main()
{
    int height = ObtainHeight();
    int width  = height * 2 - 1;

    for (int row = 1; row <= height; row++)
    {
        Repeat(' ', (width - RowToWidth(row)) / 2);
        Repeat('*', RowToWidth(row));
        cout << endl;
    }

    return 0;
}
Gonbe 32 Newbie Poster

so I spent 3 days trying to make the program and still have it not done yet :(

vs

I've done nothing and that's the problem :(

Hmmm..

Anyway, what are you supposed to use? I guess you want to implement it using an array or linked list? I assume you'd have to implement a stack and use stack-operations only such as "push", "pop" and a function to determine if it's empty or not, right? (wouldn't quite be a stack otherwise)

Assume you had functions to push and pop something on and off the stack, how would you then solve the problem you posed in the initial post? You should be able to figure that out, even without knowing a single thing about programming as long as you know what a stack is. Formulate your solution in pseudocode.

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

Now I need to do the validation for( date and madein). (1) to decrease 10% of price if date before January 2012 (2) to add 10 Rm if the madein country is Malaysia. stuck again!

Why?

If you have a day, month and year what is stopping you from determining if it's before january 2012?..

You also have a "madeIn" member. Why can't you compare it's value with "malaysia" and act based on that?

I'm not sure if you are even trying..

Gonbe 32 Newbie Poster

People are using the term "leaf" differently.. A leaf node would be a node without any children in my book. I assume you just want to delete any node from your tree, meaning you could delete the leafs too if you wanted.

I am trying to delete the leaf nodes in a bst which i have created non-recursively.

It doesn't matter how you created the tree. In the example below I delete a node recursively for example.

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

struct BSTnode
{
    int data;
    struct BSTnode *left,*right,*parent;
};

typedef struct BSTnode node;

void insert(node **root, int val)
{
    node *ptr, *newptr;

    newptr=(node *)malloc(sizeof(node));

    newptr->left    =NULL;
    newptr->right   =NULL;
    newptr->parent  =NULL;
    newptr->data    =val;

    if((*root)==NULL)
    {
        (*root) = newptr;
        return;
    }

    ptr = (*root);

    // Remark: Disallowing duplicates is intentional I guess.
    while(ptr != NULL && ptr->data != val)
    {
        if(ptr->data > val )
        {
            if(ptr->left != NULL)
                ptr = ptr->left;
            else
            {
                ptr->left = newptr;
                newptr->parent = ptr;
                break;
            }
        }
        else
        {
            if(ptr->right!=NULL)
                ptr = ptr->right;
            else
            {
                ptr->right = newptr;
                newptr->parent = ptr;
                break;
            }
        }
    }
}

//Changed: Added this helper function.
node* getLowestNode(node* root)
{
    if (root != NULL)
    {
        while (root->left != NULL)
        {
            root = root->left;
        }
    }
    return root;
}


// Changed: Added a value parameter. The first one found will be deleted.
void deleteLeaf(node **root, int value)
{
    node* replacement = NULL;
    node* deletedNode = NULL;

    // The supplied node is NULL. Nothing to do!
    if (root == NULL …
Gonbe 32 Newbie Poster

So what's your problem?..

Gonbe 32 Newbie Poster

I think the memory representation "images" are vague but I'll try anyway:

1.
Answer should be "a". You answered B. That would result in an array consisting of 3 pointers to "Foo" objects in memory, so that would be

[Foo][Foo][Foo*]

according to the notation used in your example. (I think)

2.
You answered "a" which is correct. Although I think the options are a bit vague.. (What is 'c' even supposed to mean??)
When you declare "arr" like that it is an int pointer but you cannot really say something about its value; they are not automatically initialized. (though sometimes they are,see below)


  1. Again I don't quite understand the "images" but I would choose "a" with some assumptions about what those arrows mean. arr points to an int pointer but you cannot say anything about the value of arr.

4.
Answer would be "c". You answered "b" but the pointers the array consists of are not automatically set to NULL.

Some of these questions can have multiple awnsers depending on how the things are declared. Global variables and static variables for example are automatically initialized to zero.

Gonbe 32 Newbie Poster

Hmm actually wrote something for this a loooong time ago, I'm sure it's very helpful.

#include <iostream>
#include <vector>
#include <iomanip>
const int ROWS = 8; // Change "ROWS" to set the height of the pyramid.
int v (const std::vector<int>& d, const int n, const int k) { return (k > n || n < 0 || k < 0) ? 0 : d[(((n * n) + n) / 2) + (n - k)]; }
int o (int n) { int d = 0; while (n > 0) { n /= 10; d++; } return d; }
int main(void) {
    std::vector<int> d;
    d.push_back(1);
    for (int r = 1; r < ROWS; r++) for (int c = r; c >= 0; c--) d.push_back(v(d, r - 1, c - 1) + v(d, r - 1, c));
    int b = o(v(d, ROWS - 1, (ROWS - 1) / 2)) + 1;
    for (int r = 0; r < ROWS; r++, std::cout << std::endl) for (int c = r, j, u; j = v(d, r, c), u = (b - o(j)) / 2, c >= 0; c--)
                std::cout << std::setw((c == r) * (b * ((ROWS - 1) - r))) << ""<< std::setw(u) << "" << j << std::setw(b - (u + o(j))) << "" << std::setw(b) << "";
    return 0;
}

It should adjust the widths accordingly for all size pyramids and attempts to center the numbers within their section, if I remember correctly. Due to console window limitations you should …

Gonbe 32 Newbie Poster

I am a little bit confused as to what output you want your program to have, or rather what it is supposed to represent. You don't really seem to want substrings as you also mention "ac" but you do not mention things like "cb". Would "cb" be the same as "bc" in your case?

Also (and especially if the answer to the last question is yes) how do you deal with strings like "aabbcc"?

At first sight I thought you wanted something like the following:

#include <iostream>
#include <cassert>

void print_permutations (std::string characters, const unsigned int characters_left, const unsigned int permutation_size);

int main(void)
{
    std::string characters = "abcd";

    for (unsigned int i = 1; i <= characters.length(); i++)
    {
        print_permutations(characters, i, i);
    }

    return 0;
}

void print_permutations (std::string characters, const unsigned int characters_left, const unsigned int permutation_size)
{
    assert (permutation_size <= characters.length() && characters_left <= permutation_size);

    // Recursive case
    if (characters_left > 0)
    {
        // The index the next character will be placed at.
        unsigned int current_index = permutation_size - characters_left;

        // Simply Go for every character.
        for (unsigned int i = current_index; i < characters.length(); i++)
        {
            // Swap the character at the current index with the new character
            std::swap(characters[current_index], characters[i]);

            // And solve the rest in recursion.
            print_permutations(characters, characters_left - 1, permutation_size);

            // Swap it back for the rest of the cases.
            std::swap(characters[current_index], characters[i]);
        }
    }
    // Base case
    else
    {
        // Just print the permutation. It may be shorter then the string to
        // Only …
Gonbe 32 Newbie Poster

The supplied piece of code isn't wrong. If it's not working it is something else within the program that is causing issues.

Gonbe 32 Newbie Poster

What does your design look like at the moment? (How are you handling multiple clients on the server? Threads, I/O multiplexing? You could apply the same solution on the client side to detect incoming messages and send things at "the same time" (not really ofcourse).

Gonbe 32 Newbie Poster

EPIC POST FRIEND.

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