Gonbe 32 Newbie Poster

if you want to check i can give you the whole code

I don't want to check the whole code. Appearently something is going wrong it it, so isolate the problem to a small representative section of code and show me that so I can fix it or atleast provide advance on how to fix it or what direction to think in.

Your original problem was "meanings" getting overwritten, I've answered that with how to fix it but you reply with a seemingly completely unrelated problem.

It might be a good idea to (re-)educate yourself about linked lists. Your first problem shouldn't have been a problem in the first place as you (kind of) apply the solution on the 'outer' linked list. A linked list is nothing more than a chain of structures referencing to eachother by pointers. You can add or remove individual structs from it in an intuitive way. The chain ends when it is no longer connected to another section. (programmaticaly meaning 'next' is NULL)

Gonbe 32 Newbie Poster

@gonbe
it only prints the last two meanings...

Be more specific and provide some context. I can't do anything with this.
Posting a minimal yet complete code sample helps too.

Gonbe 32 Newbie Poster

Try something like this:

#include <stdio.h>
#include <windows.h>

const int DELAY_IN_MICROSECONDS = 100;

int main (void)
{
    char symbol = 'a';

    while (1)
    {
        putchar(symbol++);

        if (symbol > 'z')
        {
           symbol = 'a';
           putchar('\n');
        }

        fflush(stdout);
        Sleep(DELAY_IN_MICROSECONDS);
    }

    return 0;
}

More information about Windows' Sleep function here: MSDN

Gonbe 32 Newbie Poster

You use some variables that aren't declared in the code. (e.g. mallocing with the size of "means" but later copying "mea" to that buffer. I will just assume this is correct, as I have no other choice)

The essence of your problem is the following line:

tmp2->meaning=tmp3;

Once you've found your word you just overwrite it's meaning. (Note that you also do not free() the possibly existing meaning in this case) Like with the words, you should go through the linked list of meanings.

Something like the following:

node2** insert = &(tmp2->meaning);

while ((*insert) != NULL)
{
    insert = &((*insert)->next);
}

// Insert now points at the memory address you should place your pointer
// e.g:
*insert = tmp3;

Quick dry-code, so consider it's working mainly. If you don't like pointers to pointers you could also do something like the following which might be easier to read:

node2* insert;

if (tmp2->meaning == NULL)
{
    tmp2->meaning=tmp3;
}
else
{
    insert = tmp2->meaning;

    while (insert->next != NULL)
    {
        insert = insert->next;
    }

    insert->next = tmp3;
}

So basically apply what you're doing to words to the meanings..

Gonbe 32 Newbie Poster

Maybe a more serious answer is in order..

Try to create a function that will prefix a given character array with "|.." and postfix it with "..|". The character section should always be atleast 2 symbols, use '.' to fill up remaining spaces if needed. (so that would be if the supplied character array has size 0 or 1) You could then create a loop to call this function with an array and call it with size 0, 1, 2 and 3 using the same array.. ('c','h' and 'm')

Gonbe 32 Newbie Poster
do
{
    printf("|......|\n");
    printf("|..c...|\n");
    printf("|..ch..|\n");
    printf("|..chm..|\n");
}
while (0);
pooja.singh.3950 commented: thanks for helping me out and can u tell me this using for loop +0
Gonbe 32 Newbie Poster

That function prints the elements of the tree from low to high. Try to not think about what happens in the recursion but think of it as reducing the problem.

If basically says this:

If you have a node to look at:

1. First print it's left subtree in order.
2. then print the current node
3. Finally print it's right subtree in order.

This will result in a sorted output because everything left is smaller than the node's value and everything to the right is bigger or equal. The "p!=NULL" condition ensures it performs no more recursive calls when you don't have a node anymore.

If you want a more non-recursive viewing point you could replace the recursive calls with their definitions. Say you call "inorder" with this tree: (So '5' is the node you pass)

        5
       /  \
      3    8
      /   
     2

I will write this as:

inorder(5-3-8-2)

The definition for that would be (excluding the stop condition):

inorder(3-2);
print 5
inorder(8);

The first inorder call would result in:

inorder(2);
print 3

(There is no right, so it would result in a recursive call with a NULL parameter which wouldn't do anything so I omit it here)

Replacing that in what we had we have:

inorder(2);
print 3
print 5
inorder(8);

Both the remaining "inorder" calls do not have any children so their recursive calls wouldn't do anything so these would just print their number. …

Gonbe 32 Newbie Poster

I'm not sure what there is not to understand about it. You start with a bigger problem then you express that into a smaller problem until you reach a base case.

The base case here would be reaching a node that is null and reducing the problem happens because insert(n) would reduce to either insert(left-child-of-n) or insert(right-child_of-n) if n is not null which is always a smaller problem.

Gonbe 32 Newbie Poster

It does it recursively. It goes down the correct path until it reaches the correct position. (at which point *leaf will be NULL)

You seem to implement a binary search tree although you cannot insert the same value more than once. I do not know if this is desired but for the example below I assume that this is a mistake and values equal to the root are pushed down the right side.

Say you have the following tree:

        5
       /  \
      3    8
      /\   /\
     2 4  6  9
    /      \
   1        7

And you want to insert another 4. Your function will first attempt to insert it into the tree as a whole. The supplied node dereferenced is not 0 and 4 < 5 meaning it is inserted into the left section. So basically the problem is reduced to inserting the key into the following tree:

      3    
      /\  
     2 4
    /    
   1    

The function is called again, but now 4 >= 3 so 4 is inserted to the left side. Reducing the problem to inserting 4 into the following tree:

4

Again the right side of this node is taken as 4 >= 4. it does not have any children however so the memory address contains a NULL pointer. So now the problem is reduced to inserting 4 into this following tree:

<none>

This is the recursion base case and a new node is constructed for the key …

Gonbe 32 Newbie Poster

X is the number you are looking for and n is the given number you should solve the equation for.

x^2 + S(x)*x - n = 0

can be rewritten as

n = x^2 + S(x)*x

Now, what happens x would happen to be sqrt(n)? It would say the following:

n = (sqrt(n))^2 + S(sqrt(n))*sqrt(n)
  = n + S(sqrt(n))*sqrt(n)

So you're basically saying n equals n + 'something' which can never be true as X is a positive integer so it will only be bigger. Ignore the reply containing i/j it is based on a false interpretation of the assignment. I left it there in case it might be useful but I don't think it will be.

You'll want to discover something about S(x)*x to find the point where it's useless to continue. You can stop searching when the following condition is true for all x that follow:

S(x)*x > n - (x^2)
= S(x) > (n - (x^2)) / x
= S(x) > n/x - x

At what point does that become true though? If it some point this condition is met, it needn't be the case for x's following it. While the sum of digits does grow in a pattern it "drops" every now and then but it starts at a higher point than where the previous drop started of the same digit count. Maybe you can think of something for this. (or S(x)*x will always be bigger than n-(x-2) …

Gonbe 32 Newbie Poster

Hmm how do you brute force it currently? Some optimizations (but it's still brute forcing) would be to:

  • don't count the amount of digits per attempted number (or maybe not at all) instead start at i=10, j = 1 where you multiply i by 10 everytime your number hits i and increment j. j would be the S(x)

  • Because you can determine S(x) somewhat cheap (I think the difference of looping you'll get gains you more than you lose by keeping track of j) you could use it to lower the search domain. You should search until sqrt(n) - x*j. You should probably also search from that number going down instead of starting from 0 and going up.

This is probably something you've tried already, at first thought I wouldn't know a proper optimization (Maybe look for a low point under which is no longer useful to search, or number to skip based on previous results)

-edit-
Hmm misread S(x) as the digit count instead of the sum of digits. Maybe treat S(x) in the lowest case with a value of 1 and then search till sqrt(n) - x

Gonbe 32 Newbie Poster

Using the above approach with your initial example (which is a lot simpler) you'd get the following pathlist:

1->2: a<ref:2->2>
1->4: (b + (<ref:1->3><ref:3->4>))
2->2: b*
2->3: <ref:2->2>a
1->3: <ref:1->2><ref:2->3>
3->4: (a + b)

Then writing 1->4 out results in:

1->4: (b + (<ref:1->3><ref:3->4>))
1->4: (b + (<ref:1->2><ref:2->3>(a + b)))
1->4: (b + (a<ref:2->2><ref:2->2>a(a + b)))
1->4: (b + (ab*b*a(a + b)))

Which is the same as

b + (ab*a(a + b))
Gonbe 32 Newbie Poster

Definately possible but quite challenging to find an optimal solution. Going to write down a quick first thought..

To make your example a little bit more complex say there's the following lines as well:

StateNumber  NextStateC
2            1
3            1

Given have the table filled already every branch of paths would resulting in building up it's own operand of an '+' (or).

From the start state you'd be able to deduct the following paths:

1 -> 2 : a
1 -> 4 : b

then you continue with 2 and 4. Information known about 2:

2 can reach 2 with b*.
2 can reach 1 with c.
2 can reach 3 with a.

This means an extension of our paths. First the directly described paths:

2 -> 2 : b*
2 -> 1 : c
2 -> 3 : a

After adding new paths you should always try to deduce new paths from them. in this case it would add the following. (you should deduct new paths after every deduction too, basically any path addition):

So adding 2->2: b* would result in: All paths that start with 2 get preceded by b* and all paths that end with 2 would be extended with b*. I reference paths in that's how you'll likely want your program to deal with it and it makes it easier for me to explain. The resulting paths after this addition are:

2 -> 2 : b*
1 …
Gonbe 32 Newbie Poster

Infix, prefix and postfix are merely notations. For example

1 + 2 : Infix, The '+' operator is written between the operands it applies to.
1 2 + : Postfix (Reverse Polish Notation), the '+' operator follows it's two operands.
+ 1 2 : Prefix (Polish Notation), the '+' operator preceeds it's operands.

Precedence rules ("order of operation") have nothing to do with ASCII values, as mentioned. These are just rules made to clarify unambiguously which procedures should be performed first in a given mathematical expression.

These rules are explained in many places, for example here: http://en.wikipedia.org/wiki/Order_of_operations

e.g. if you have something like the following:

9 / 2 + 5 * 7 

Precendence rules result in it having to be interpreted like this:

((9 / 2) + (5 * 7))

Operator associativity is also something to note. More on that could be found here:
http://en.wikipedia.org/wiki/Operator_associativity

In essence it determines how operators with the same precedence are grouped in the absense of parenthesis. For example:

1 + 2 + 3 + 4 + 5

Would have to be interpreted as the following because '+' is (generally) left-associative:

((((1 + 2) + 3) + 4) + 5)

If you're looking to parse mathematical formula's you might want to look at Dijkstra's Shunting Yard algorithm. Information on this can be found here:

http://en.wikipedia.org/wiki/Shunting-yard_algorithm

Gonbe 32 Newbie Poster

An easy approach would be to determine the mean in the first pass through the file, then go through the file again to determine the standard deviation by squaring the differences of every number with the mean and then take the square root of the average of those values.

There are also algorithms which calculate the standard deviation in a single pass ("on the fly") but those are more complicated and shouldn't be that difficult to find by a simple google search.

Gonbe 32 Newbie Poster

"Multiple switch" case, I am not sure what you mean by this. Checking for multiple cases is what you'd typically use a switch for so yes, multiple "case" statements are allowed.

Nesting a switch within a switch is also allowed. The switch body is just a normal or compound statement which can contain any other valid c labels. In fact, you could also use case statements there without a switch.

A little example:

#include <stdio.h>
int main()
{
    int a = 1, b = 2;

    switch(a)
    {
        case 1:
            printf("Falling through..\n");

        case 2:
            printf("Falling through..\n");

        case 3:
            printf("Falling through..\n");

        case 4:
        {
            switch(b)
            {
                case 1:
                    printf("b is 1.\n");
                    break;

                case 2:
                    printf("b is 2.\n");
                    break;

                case 3:
                    printf("b is 3.\n");
                    break;

                default:
                    printf("b is undefined!\n");
                    break;
            }
        } break;

        case 5:
        {
            case 6:
                printf("a is 6!\n");
                break;
        }

        default:
            printf("At the bottom.\n");
    }

    return 0;
}

When run, it will output:

Falling through..
Falling through..
Falling through..
b is 2.

because 1 is one, but the case bodies of the other switch don't break out of it using 'break'. As a result the case statements are executed in order. This is called "fallthrough".

At some point the body for case 4 is reached which contains a new switch statement. This is valid. For example purposes I DID add 'break' statements for every case now which is why only the following is shown:

b is 2.

Note that a break will only break …

Gonbe 32 Newbie Poster

1) you are expecting us to remember one post you made elsewhere out of hundreds we read daily

You've made the reference to a previous post in another thread yourself. In that case, yes. I do expect you to remember it.

2) sarcasm requires knowledge of the one making sarcastic remarks. All I understand is from what you posted above.

Knowledge about recent events also aid and you were present in those.

3) on a forum, a smily generally hints at sarcasm. No smily, you must be simply daft.

As someone who dislikes smileys I can tell you there's more than that. I don't see writers using smileys in their books (thanks god) and they seem to get their intent across just fine.

The combination of the first two lines ending with '!' and the statement following it which you even quotes should be way obvious. If you're incapable of detecting it then I consider it your issue. But sure, I can omit sarcasm from my posts from now on. Posting a sneer trying to ridicule a post while you are in fact the one not understanding the post at all has the opposite desired effect for you, though. I guess I'll view it as karma.

4) whether you agree or not, you are not to post working answers. Period.

The community rules don't seem to mention this. I'll determine on a per-post basis how I could help a user best, thanks.

WaltP commented: If you have a problem with the way things are supposed to be done, keep it out of the responses and make your points in the Feedback Forum. Stop cluttering up other people's threads with your rants. -3
Gonbe 32 Newbie Poster

So what doesn't work? You need to give us informations if you need help.

how can I do it reading from the file?

It's clear what he wants to achieve. Going by his code sample it's also clear what isn't working. But I know you have a reading disability so I'll not bully you with it. ;)

@izic

The problem you're having is that you made a function, modifyspace, which wants a destination and a source array but with the current setup you read one character at a time from the file. In order to use your function (doing a basic assumption on how it works) you would have to store the characters you read into an array first. Like your first example this imposes a limit on the input and isn't really error-prone.

A better solution would be to process characters as you read them so that once you're reading a next one the previous one(s) can be discarded as they are already discarded, written to file, printed to stdout or whatever you want to do with it.

This is likely a pretty easy thing to do as your 'modifyspace' function contains the algorithm for this already. Instead of looping over an array and accessing each element you use the character read from the filestream.

Let us know how it goes. Post the code you developed if you're running into issues.

Gonbe 32 Newbie Poster

and making himself look... well... you know... he just didn't delete the explanation himself and not post it.

Sarcasm. Do.. you.. understand.. it?

Appearently you fail to grasp anything so I make it clear: In case it wasn't obvious in the other thread I don't agree with not posting solutions so this was formulated in that specific way as a slight ridicule towards it.

Feel free to private message me in case you're ever having troubles reading.

Gonbe 32 Newbie Poster

The more you backtrack like this (you've done it twice that I know of today) maybe you should give it some thought before posting... Maybe??? ;-)

Oh look, one of the clowns from the other thread. Nice contribution to this thread as well bud. I assume you're still upset about the discussion in the other thread? Maybe you should reply to the questions asked in threads instead of contributing absolutely nothing and merely attempt to de-rail the thread by attempting to flame someone who is actually trying to help the OP... Maybe??? ;-).

Besides, I can't care less about your opinion so you're just wasting your time. I'm honored you're tracking my posts though. I feel bad for having upset you so easily. Oh wait, I don't.

exactly, my thought was just like this, but my prob was that should i use a 3D Dp here ? because for n,k and one for 1 or 0 ?

Yeah that's what I would do. The 3rd dimension having a fixed size of 2. (so in that sense you could also view it as 2 2-dimensional arrays)

-edit-

To elaborate on the "should" part of your question: you'll want to track 2 different types of subsets. There's not 1 generic sub-problem once going into the recursion but 2. (the n,k combination could be identical but the context can be different; The 'outer problem' ended in either a 1 or 0. So this context provides a slightly different problem …

Gonbe 32 Newbie Poster

Giving it some thought you should ignore the previous post as I think it's a poor way of solving it. it will work and it pretty easy but after thinking about it dynamic programming would make this pretty easy to solve as well without going into mathematics that much while yielding better performance.

The result of n,k could be formed depending on the last bit and then entering recursion to check subproblems. (if the bit is 1 (n-1, k-1) otherwise (n-1, k)) you can use dynamic programming to speed this up. It's also incomplete the way I describe it now but the essence of it should work.

if it ends with a 0 you could see it as a direct subproblem but if it ends in a 1 you have to take into account that 1 and it's not a direct subproblem. (but very closely related)

-edit-
actually, if it ends in one it would default to the subproblem of ending_with_zero(n-1, k) + ending_with_one(n-1, k-1). The first would result in the ending of 10 so k remains the same while the other would result in the ending of 11 so k is lessened and the recursion should mind that ending in a 1 again would lessen k by 1 again.

Gonbe 32 Newbie Poster

There's multiple ways to do this. This could be solved with (discrete) math alone although I think you're aiming for a more brute-force approach right?

In that case a logical start would be to implement the AdjBC() function. You don't have to start at the most significant bit for obvious reasons so it's not that hard. You could start with something like this:

    // Just random to illustrate.
    int number = 100;

    // Going through the bits starting at the least significant bit.
    while (number != 0)
    {
        // Access your current bit with "(number & 0x1)".
        printf("%d", (number & 0x1));

        // Advance to the next bit by bitshifting.
        number >>= 1;
    }

You have a basic structure now to access every bit of a number so the remaining task, determining the result of AdjBC(), should be something you could manage now.

From then on determining x using n and k would be easy to brute-force. (but inefficient) Seems like a pretty fun problem to solve, might try it once I am home..

Gonbe 32 Newbie Poster

I didn't really go over the code yet but how does it run for you when you change

struct node *list1, *list2;

to

struct node *list1 = NULL, *list2 = NULL;

?

Gonbe 32 Newbie Poster
  1. You shouldn't really use gets().

  2. You're mixing scanf() and gets(). It's possible, but not recommended. Keep in mind that gets() looks for a newline (or eof) while scanf() tries to obtain the minimal and will keep the newline in the stream. (in this case) You could place a "fflush(stdin)" at the start of your loop although I believe technically this is undefined as you're applying it on an input stream. You could read characters until (and including) the newline left by scanf before your next gets() too, but the difference is probably not all that relevant to you at the moment..

    scanf("%d", &a[i].age,&a[i].marks);
    printf("Enter the marks of student");
    scanf("%f", &a[i].marks);

  3. This is a bit confusing and looks like the result of you having tried multiple things. I assume the first line is an error you can identify yourself as well.

As far as "loop not running" goes, you'd have to elaborate on what you mean by that exactly..

Gonbe 32 Newbie Poster

Start simpler. Create a function with the following signature:

void repeat_character(const char symbol, const int amount)

what it should do is it prints 'symbol' to stdout 'amount' times. So, print_character('2', 5); should print

22222

Once you have that solving your original problem should be easier. If you don't know how functions work yet you cuold either read into it, or you could fill in the following section between parenthesis:

void repeat_character(const char symbol, const int amount)
{
}

as if you were coding in 'main' where 'symbol' and 'amount' can be used without having to declare them in the body or assign values to them. Once you've managed to build this you could post it here and we could proceed with the rest.

-edit-
You can modify the function signature I suppose (e.g. non-const 'amount' or using an unsigned integer) though it's goal will be the same. It will make your initial problem trivial.

iamthwee commented: Much better advice +14
Gonbe 32 Newbie Poster
    char *p1="Name";                // Non-const pointer pointing to non-const char.
    const char *p2="Name";          // Non-const pointer pointing to constant char.
    char const *p3="Name";          // Alternative syntax for p2.
    char *const p4="Name";          // Const pointer pointing to non-const char.
    const char *const p5="Name";    // Const pointer pointing to const char.

    ++p1;   // Fine:  p1 isn't a const pointer.
    ++*p1;  // Fine:  p1 points to chars who aren't const.
    ++p2;   // Fine:  p2 isn't a const pointer.
    ++*p2;  // Error: p2 points to a const char and you're trying to increment it here.
    ++p3;   // Fine:  p3 isn't a const pointer. (p2 and p3 are basically declared the same way but in a different syntax)
    ++*p3;  // Error: p3 points to a const char and you're trying to increment it here.
    ++p4;   // Error: p4 points to non-const data, but you're trying to modify the pointer itself here, which is const.
    ++*p4;  // Fine:  p4 itself is const but the data is points to is non-const. Dereferencing and then incrementing is fine as a result.
    ++p5;   // Error: p5 is a const pointer as well as it pointing to const data.
    ++*p5;  // Error: p5 is a const pointer as well as it pointing to const data.

Added some comments with each statement that should answer your question.

Uhm, I mean, here's a hint! It has to do with asteriks and the position of the const keyword! More precisely you should look up the difference between "const char" and "char

Gonbe 32 Newbie Poster

Really, if that was the case why don't we all just post up the answers to everyones' homework?

You tell me. Just because 'everyone' (which is not even true, but okay) does something, it doesn't mean it's logical or the best thing to do. (A controversial example would be religion if you'd ask me)

In fact, why don't teachers just bypass giving homework altogether and give out questions with model solutions?

If you've ever gone to school you'd know that partially you do get provided examples of good practices. Generally these are subsets of bigger problems that have to be solved later but they can sometimes be a larger example too as these introduce additional complications.

Your statement is very short-sighted as it implies teacher ONLY give homework, which is ofcourse not true.

If you really expect someone to buy your BS at least give plausible reasoning, not some BS you just pulled out of your a##.

Right back at you. Everything you said so far was completely biased.

Again, you clearly miss the purpose of setting homework. To you, it's more instructional to just hand out solutions. Hands up anyone who agrees with this? Come on now, don't be shy.

Again, you want to try to get people behind you to back you up. Should I interpret this as an obvious sign of you being insecure about your own stance? Provided that I seem to have provoked you I guess I …

Gonbe 32 Newbie Poster

^^ "The OP gets a freebie answer and passes his course". Sure he gets an answer. What he does with it is his choice though. If he is indeed one of the people that hands this one in without trying to understand it himself, do you really think your supposedly brilliant 'nudges in the right direction' would have learned him anything? It wouldn't. He would do the absolute bare minimum and not really attempt to learn. Sure, he might have to look some things up and will likely paste some snippets but if he's truly looking just to get rid of the assignment it's all in vain anyway.

I assume that people who ask things actually have the intention to understand it. An example code will serve as a good point to start in my opinion and could serve as a base of other question.

Oh and please refrain from calling people you do not know 'class A idiots', you wouldn't want to be seen as one yourself I presume. And I am already contributing to open-source projects; One activity doesn't rule out the other.

Have a good day, bright light.

iamthwee commented: I am Iamthwee and I disagree with this post. -3
Gonbe 32 Newbie Poster

This assignment contains easy to identify subtasks which can be expressed in their own functions. Following this idea I would suggest something like the following:

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

// The maximum length of a string.
#define STRING_MAX (40)

// Function declarations/prototypes.
void reverse_substring (char str[], int start, int end);
void reverse_words     (char str[], const int length);

// Reverse the substring within 'str' starting at index 'start' and ending at index 'end'.
void reverse_substring (char str[], int start, int end)
{
    // Little check to ensure correct parameters.
    // Not checking if end < strlen(str) so str doesn't have to be NULL-terminated.
    assert (str != NULL);

    char temp = 0;

    while (start < end)
    {
        // Store the character that's on the left side.
        temp = str[start];

        // Overwrite the character that's on the left side with the one that's on
        // the right side. And move the left index one to the right afterwards.
        str[start++] = str[end];

        // Overwrite the character that's on the right side with
        // the backup of the one that used to be left.
        str[end--] = temp;
    }
}

// Reverse the contents of words in a given string.
void reverse_words (char str[], const int length)
{
    // Not checking for string length so it doesn't have to be NULL-terminated.
    assert (str != NULL);

    int i           = 0,    // Counter to iterate over the string.
        start_found = 0,    // Flag that shows if we're looking for the beginning or the …
iamthwee commented: Yes you deserve this +0
happygeek commented: some more well deserved neg rep from me... -2
Gonbe 32 Newbie Poster

Introducing a flag with additional code to set and check it seems like a poor solution, especially when it's not needed. Doesn't simply moving the printing instruction out of the loop do what you describe?

main()
{
    FILE *file = fopen ("COMMAND.txt", "r");
    FILE *file1 = fopen ("LOG.log", "a");

    if (file != NULL)
    {
        char line [255]; /* Max line Size*/

        fprintf(file1, "######\n"); /* it suppose to print on the first line only when u executed */

        while (fgets (line, sizeof line, file ) != NULL) /* Reading a line */
        {
            char first[10];
            if (sscanf(line, "%9s", first) ==1)
            {
                fprintf(file1, "%s\n", first);
            }
            printf(line); /* print on command prompt */

        }
        fclose (file);
        fclose (file1);
    }
    else
    {
        perror ("Please check the file name and try again!");
    }
}
Gonbe 32 Newbie Poster

While this doesn't even deserve an answer as you don't even ask a proper question (You just dump your code and state "it doesn't work!") you could try this.

I'm not going to explain anything about it I guess as you didn't ask me to. It's also a naive implementation that could be optimized a lot but I'm not going to waste time on someone who doesn't even put in an effort to post his thread.

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

int get_digit_count(unsigned int number);

// Obtain the amount of digits a number consists of.
int get_digit_count(unsigned int number)
{
    int digits = 0;

    do
    {
        // Cut off the last digit
        number /= 10;

        // Add this digit to the total number of digits.
        digits++;
    }
    // Do this until there are no more digits left.
    while (number != 0);

    return digits;
}


// Entry point of the application. Naive implementation 
// of an algorithm to find armstrong numbers. 
int main(void) 
{
    int i                 = 0,    // Integer for iterating.
        limit             = 0,    // The limit of the search.
        digits            = 0,    // The amount of digits for the current number.
        powered_digit_sum = 0,    // The sum of the digits pow'd by the number of digits
        current_number    = 0;    // Current number looked at.

    printf("Enter the limit of the search (inclusive): ");
    scanf ("%d", &limit);

    printf("Calculating armstrong numbers from 0-%d (inclusive)..\n", limit);

    // Go through all numbers from 1 till 'limit' (inclusive)
    for(i = 0; i <= limit; i++) …
WaltP commented: Then why did you bather doing his moework for him in the first place? -3
Gonbe 32 Newbie Poster

Hello Daniweb.

Scenario
For a project we have to write a irc server. For this, we first wanted to investigate what kind of server architecture we should apply. (e.g. multithreading, multiplexing, multiprocessing etc.) We've written simple servers which implement different architectures. The servers basicially receive a message, and then send that message to every user connected to the server.

The next step would be to write a testclient. The client can be given a bunch of parameters to specify things like: "How many clients will the program emulate?", "What's the data size?", "How many times will that data be send?", etc.

The solution so far
I've written this server, but there's a problem I do not know the correct mechanism for to realise it. The way my program is waiting at the moment is as follows:

  • A main thread spawns a number of processes using fork(). (working on linux) These processes will represent clients.
  • Each process executes a function which connects to the server.
  • Once connected, the process spawns 2 threads. Both threads will be given the socket for the server connection. One thread will be used for writing, the other for reading.

The problem:
The problem, is that when you create multiple clients using the application, the first process might already send data before the 50th client is even created. The server will receive this message and send it back to less users than i expected it to, which results …

Gonbe 32 Newbie Poster

Hello Daniweb,

I've ran against an issue in my code and i'm not sure why I receive an error. I've managed to reproduce the error with the following code:

#ifdef _WIN32
#define PERFORMANCE_METING
#endif

#ifdef PERFORMANCE_METING
#include <windows.h>
#endif

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

typedef enum { FALSE, TRUE } Boolean;

int main()
{
    return 0;
}

This code gives me the following error for the line where the typedef is:

error: syntax error before numeric constant

Could anyone tell me why what I did is not allowed?
Besides that I was wondering if it was possible to check 2 symbols in 1 line with ifdef. (e.g. ifdef _WIN32 && PERFORMANCE_METING or something) or can I only use #if defined(_WIN32) && defined(PERFORMANCE_METING) for that?

Thanks in advance,

Gonbe.

-edit-
It doesn't seem to like include <windows.h> for some reason.
Do not know why though.

-edit-
Windef.h has a definition for FALSE and TRUE.. guess that's the issue.

Gonbe 32 Newbie Poster

I have just installed the latest nforce chipset drivers, and the issue appears to be gone now. I can't say for sure because it does not happen on all files, but it hasn't occured since the update yet.

Will update this post if the problem persists. Thanks!

Gonbe 32 Newbie Poster

What sort of file are you deleting?

The issue occured on video files (.AVI) from what I have tested.
(ranging from 200MB to ~4GB) I have not tested other files yet, except very small files like txt files.

I've also checked the seagate website for new firmware, but there does not appear to be any. On the website I also found their HD tool called SeaTool. I've ran that partially and the 3 short tests showed the following to me:

SMART: Fail.
Short DST (Drive Self Test): Pass.
Short Generic: Pass.

However, my other harddrive (which i have for about 3 years now and never had anu issues with, also from seagate) also seems to fail that SMART test.

The application advices to download the DOS version of SeaTool and boot my computer with it. This is something I will be trying soon.

Another thing I suppose I can try is updating the chipset drivers for my motherboard.

A little more info about the drive:

Model Number: ST31500341AS.
Firmware revision: CC1H.
Gonbe 32 Newbie Poster

Hello Daniweb community,

Recently I bought a new harddrive. Below is a link to the manufacturer's website and the model:

http://www.seagate.com/ww/v/index.js...D&locale=en-US

I connected the drive according to the instructions and then booted up my computer. The drive got detected in the BIOS so i booted up Windows. I then went to the following section: (rough translation as I run a non-english version of windows)

Control Panel -> Computer administration -> disk administration

There I partitioned the disk as a primary disk and formatted it. The partition received the full capacity of the drive (1397,26GB) and I selected "quick format".

At first sight, the drive seemed to work well. However, I soon found out that when I deleted a file from this disk it didn't really get removed while the computer was on. When I delete a file it looks deleted. But when I leave the directory and come back later it's back again. When i try to delete the file once more I now receive the following error message (translated):

Cannot delete <filename>. Access denied.

Check if the disk is full or protected against writing and that the file is not currently in use.

When I reboot my computer the file does not get shown anymore and appears deleted as it should be when i deleted it the first time.

I thought it might have been because i selected a quick format instead of a regular one so i formatted the …

Gonbe 32 Newbie Poster

As far as I know Volatile is used when you don't want the compiler to perform certain optimizations with regards to value changes. (It is as if you say: "The value of this variable may change, even if this doesn't happen in the current program". This may happen in embedded systems for example where this shared memory occurs more.

A simple example would be:

int main(int argc, char* argv[])
{
    int* test = (int*)0x1234;

    while(*test == 2)
    {
    }
}

In this program the value at address 0x1234 will be obtained and checked if it matches 2. If not, the body of the while loop will be executed, but it's empty. When the compiler optimizes (don't know if this goes for all), it doesn't actually check the value at 0x1234 again, but assumes it has not changed. (because there was no code that changes the value there) In case another proces changes the value at 0x1234 that this code will make use of, you can use volatile.

Gonbe 32 Newbie Poster

What you are doing now is trying to use a functor. (overloaded () operator for that object)

Use the initialization section of the constructor to initilize the object:

Desktop::Desktop() : otwarte_okna()
{
    x1=y1=0;
    x2=y2=1000000;
}
Gonbe 32 Newbie Poster

eof becomes true when it has already read past the end of file.

Gonbe 32 Newbie Poster

Hello Daniweb,

I'm trying to create a very simple shell for practicing purposes, but i'm a little bit puzzeled about the usage of execve, the function i use to execute a file.

The code fragment underneath shows my usage:

childPID = vfork();

        if (childPID == 0)
        {
            execve(input.process, input.parameters, environ);
            printf("[!] %s.\n", strerror(errno));
            _exit(0);
        }
        else
        {
            waitpid(childPID, NULL, 0);
        }

In this example I have the parameters used use the following (strings are NULL terminated):

input.process: "ls"
input.parameters: NULL pointer.
environ: A variable defined in unistd.h with the current environment settings.

When I execute the application like this i get the following:

[!] No such file or directory.

So i decided to investigate the environment variable. One of the data contained in it is:

PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/MyUsername/bin

So one of the path paths in the path variable is "/bin" so I don't quite understand why "ls" doesn't work.

So then I tried the input "/bin/ls" instead of just "ls" and then the program does seem to work. So my question is: Why can't I provide a relative path when bin directories are specified in the PATH variable of the environment?

Gonbe 32 Newbie Poster

I'm not sure if I understand your question correctly, but you could just copy the data like you would with non-allocated data. So something like this is what I mean:

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

#define AMOUNT_OF_DATA 20

int main (int argc, char *argv[])
{
    int *allocatedData = (int*) malloc(AMOUNT_OF_DATA * sizeof(int));
    int i = 0;

    //putting data in the allocated memory:
    for (i = 0; i < AMOUNT_OF_DATA; i++)
        allocatedData[i] = i + 1;

    printf("Contents of allocatedData:\n");
    for (i = 0; i < AMOUNT_OF_DATA; i++)
        printf("%d ", allocatedData[i]);

    //Make a copy
    int dataCopy[AMOUNT_OF_DATA];

    //Copy the data from the allocated memory to the new variable.
    for (i = 0; i < AMOUNT_OF_DATA; i++)
        dataCopy[i] = allocatedData[i];

    //Freeing the allocated memory
    free(allocatedData);

    //Showing contents of the copy
    printf("\n\nContents of dataCopy:\n");
    for (i = 0; i < AMOUNT_OF_DATA; i++)
        printf("%d ", dataCopy[i]);

    return 0;
}

Will result in the following output:

Contents of allocatedData:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Contents of dataCopy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Gonbe 32 Newbie Poster

Your code seems to contain a lot of errors.

You want to create a class called DayOfTheWeek that represents a day of the week. It looks like you have tried to store the actual data in a string object that you made private. That's an idea that could work. (The assignment would like you to store things like "Mon" it seems. You could also consider using an enumeration for this) You made 2 variables for 2 days (mon, tues) which makes no sense to me and is probably not what you wanted either. After all, it can only be 1 day at a time. (If you'd like to have a variable for each day, you could use the datatype "bool")A single datamember would be sufficient. If you'd use an enum to represent a day, your code could look like this at this point:

#include <string>

class dayOfTheWeek
{
    public:
        enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Undefined};
        
        dayOfTheWeek();
        dayOfTheWeek(Day _day);
    
    private:
        Day day;
};

//Default constructor.
dayOfTheWeek::dayOfTheWeek() : day(Undefined)
{
}

//Constructor to set the day directly.
dayOfTheWeek::dayOfTheWeek(Day _day) : day(_day)
{
}

As you can see I added 2 constructors instead of only a default one. Also the way of initializing the data members might be unknown to you, if you'd like to know more you could search for "initialization section".

On the next question it asks you to create the following: setDay, printDay and getDay. This is where the main issue lies …

Gonbe 32 Newbie Poster

Alternatively you could set your condition as the loop condition. A cunstruction I would use would be a do-while setup, as displayed below:

int i;

do
{//return from the loop only when the input is zero
	printf("\n1: Stack1\n2: Stack2\n0: to return\n");
	scanf("%d",&i);
	
	switch(i)
	{
		case 1:		printf("1");								break;
		case 2:		printf("2");								break;
		case 0:		printf("Thank you for using the service");	break;
		default:	printf("Give a Valid Option");				break;
	}//end of switch - case
}//end of while
while(i != 0);
Gonbe 32 Newbie Poster

Are you certain that the crash occurs at the getline call? I'm not on a *nix system, so I can't run your code, but that call looks okay given this and what I see in the code. Did you discover the crash point by stepping through with a debugger? If not, consider adding more flushed outputs to verify whether the crash occurs there or later.

I added a printf statement before the getline statement, and another one after it. On execution the printf statement that came before getline was executed correctly, and then the segmentation error showed up before the printf statement that came after getline was displayed.

[edit]In fact, isn't the following guaranteed to write to a null pointer given your example?

void extractWords(char *process, char *parameters[], unsigned int *parameterAmount, char *buffer, unsigned int bufferSize)
//TODO: Words between quotes are 1 word, even if there's a whitespace between them.
{
   int i = 0;
   *parameterAmount = 0;
   *process = 0;

This was indeed the error! I've modified this (process should have been a pointer to a pointer as I wanted to modify the address itself) and now the code works. (aside from some other bugs that i fixed now aswell) I still do not know why the program would crash at the getline and not at this specific asignment though.

Gonbe 32 Newbie Poster

Hello.

I'm writing a program in C that should ask for a line of input, and extract the process name and parameters. This doesn't have to be totally bulletproof at this point. An example input could be:
"Hello these are parameters". On this example "Hello" would be the string i want as process name, and the other words are parameters. I'm using getline (http://linuxmanpages.com/man3/getline.3.php) to get input from stdin.
I don't allocate more memory for the individual words but instead store pointers of the main string, and replace spaces with null characters. The program worked before, but after I made some changes I get this segmentation error which I can not get rid of. (Neither can i find what changes were made since the working version) I also tried allocating memory for the "buffer" variable in the acquireInput function myself instead of letting getline do it, but the result was the same.

The part of the program where my code crashes looks as follows:

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

struct Command
{
    char* process;                  //First word contained in buffer.
    char** parameters;              //Array of memory addresses contained in buffer that are the beginning of parameters. (Dynamically allocated)
    unsigned int parameterAmount;   //Variable that holds that amount of parameters.
};


char* acquireInput(struct Command *input, unsigned int *parameterAmount);
int isWhitespace(char character);
void extractWords(char *process, char *parameters[], unsigned int *parameterAmount, char *buffer, unsigned int bufferSize);

int main(int argc, char *argv[])
{
    char *buffer …