deceptikon 1,790 Code Sniper Team Colleague Featured Poster

However java does not seem to allow 2 returns in the same method

That's not correct.

and considers the following code as not having a return statement.

This is correct. Not all paths end in a return statement, so your compiler is complaining. You have a return for the if clause, one for the else if clause, but no return for the implicit else clause. It doesn't matter that the implicit else clause is logically impossible, your compiler isn't checking the conditions, only the paths.

In this case you can turn the else if into a simple else to fix the problem, because that wouldn't break your logic.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how do i fix the error that says "E:\Pet\src\Pet.java:56: error: class PetTest is public, should be declared in a file named PetTest.java public class PetTest"

That's what I was talking about with my addendum that if both classes must be public, they should be split across two files (just like the error says).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
for i in range(0, n):
    List.append(random.randint(0,1000))
    return (List)

This generates one number, appends that one number, and returns immediately on the first iteration of the loop. You need to move the return statement outside of the loop:

for i in range(0, n):
    List.append(random.randint(0,1000))

return (List)
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I wasn't aware of that.

Which means you didn't read the reference link in my initial reply. Sometimes I wonder why I even bother.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

method expects address of the variable/ pointer varible instead of passsing value of the variable while calling the method
but you called this method by passing the value directly so that is the reason you got skipping over the function call

That's a good guess, but you're wrong. The argument evaluates to a pointer, it already represents an address, so no address-of operator is needed in this case. The problem is that reverseString() is all borked up; it shouldn't even compile. Anyway, replace reverseString() with the following and watch the problem go away:

char *reverseString(char *original)
{
    int i, j;

    for (i = 0, j = strlen(original) - 1; i < j; i++, j--) {
        char temp = original[i];
        original[i] = original[j];
        original[j] = temp;
    }

    return original;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I was also told to stay away from classes completly until he's ready for me to move in that direction.

That sounds like the kind of thing a teacher who's only a step or two ahead of you in the learning process would say to avoid being embarrassed.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

When a simple-escape-sequence like '\n' is evaluated, what would be the result?

It's evaluated as the platform-dependent character for a newline. For example, on Linux '\n' will be evaluated as LF (ASCII 10) while on Windows it'll be evaluated as CRLF (ASCII 13 + ASCII 10). But it's totally irrelevant unless you're bypassing the standard I/O framework because those translations will be done under the hood. Your program will never see anything except '\n'.

How I can show ASCII 10 as a character?

Just print the value 10 in character context:

printf("ASCII 10: '%c'\n", 10);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I have yet to effectively use these expressions.

It's fairly straightforward when compared with an if..else statement. This:

x = (condition) ? foo : bar;

Becomes this:

if (condition) {
    x = foo;
}
else {
    x = bar;
}

IF you don't need to make an assignment and are instead just performing an action with a side effect, this:

(condition) ? someAction() : someOtherAction();

Becomes this:

if (condition) {
    someAction();
}
else {
    someOtherAction();
}

That's really all the ternary operator does. A benefit is that it can be used in an enclosing expression where the if..else statement cannot.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It really depends somewhat on how you declare your pointer. For example, a static or global pointer will be default initialized to null. A local pointer will contain random garbage if not explicitly initialized, just like any other local variable.

Best practice is to initialize your variables in all cases to avoid having to remember and apply the different rules to the given situation.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I am still kind of confused.

Consider speaking with your teacher instead of looking for help online. I could clear up your confusion on this topic easily with a little bit of hand waving and a whiteboard, but it's tedious to no end using forum posts.

Can you o into more details please

It really boils down to this: The address of the variable a is 0xFF2a. If the size of the variable a is 4 bytes then the address of the next variable (b in this case) is 0xFF2a + 4, or 0xFF2e. Repeat the process to get the address of every variable in the program.

Once you have the address of every variable, learn how pointers work and then use paper and pencil to write down the result of each executable statement in the program. If you know how pointers work, it's trivial. If you don't, it's impossible.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The logical OR (||) and bitwise OR (|) are also subtly different. Sometimes you'll get the same result and sometimes you'll be surprised, so I'd recommend not using the bitwise OR in situations where you clearly want a logical OR. This is one of those situations, so your test should be:

if ((a[0] == 'y') || (a[0] == 'Y'))
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The annoying use case is this:

for (vector<int>::size_type i = 0; i < v.size(); i++) {
    cout << v[i] << ' ';

    if (i == v.size() - 1) {
        cout << endl;
    }
}

C++11 offers the auto keyword for initializer type deduction so that we can avoid verbose and ugly types like vector<int>::size_type. However, the naive attempt doesn't work:

for (auto i = 0; i < v.size(); i++) {
    cout << v[i] << ' ';

    if (i == v.size() - 1) {
        cout << endl;
    }
}

The reason it doesn't work is because 0 doesn't match the type of v.size(). Worse, v.size() is an unsigned type while the literal 0 is a signed integer. At most there will be a warning, but that's still annoying, so I set out to come up with a better option that's consistent across the board and has a more conventional syntax.

Option 1: decltype

C++11 also offers the decltype keyword for deducing the type of an expression or entity. In this case we can deduce the type of v.size() and use that for the type of i. Everything works nicely with perfect type matching and no warnings, but it's kind of ugly syntax-wise:

for (decltype(v.size()) i = 0; i < v.size(); i++) {
    cout << v[i] << ' ';

    if (i == v.size() - 1) {
        cout << endl;
    }
}
Option 2: Iterator arithmetic

An option that exists prior to C++11 is by using iterator …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Quote your string in the SQL statement:

string OrdersLine50CustomerSQL = "SELECT cashID, cashQTY, cashDescription, cashSupplier, cashDate, cashCost, cashSell, accAccRef_FKID from cashOrders WHERE cashOrders.accAccRef_FKID = '" + CustomerID.ToString() + "'";
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

file_to_check.close();

That's not necessary. If the file is open, the destructor for ifstream will close it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So in the following code, is message an array because it doesn't really look like one?

Yes. The string literal is actually stored as and has a type of array to const char. When used in value context it evaluates to a pointer to the first element, which is why you can assign it to a pointer. It's also a holdover from C that you can assign a pointer to const char (in this context) to a pointer to char, which would normally be illegal without a cast.

To be strictly correct, any pointers to a string literal should have a type of const char* because string literals are technically supposed to be read-only.

I thought that the number in the [] of a char array would dictate how many characters are in the array but in this case it's how many strings all together. What have I missed here.

You're storing an array of pointers, the size of the array dictates how many pointers the array can hold, which in this case is 4. It helps to think of int instead of the pointer to char aspect is confusing you:

int members[4] = {1, 2, 3, 4};

The fact that the array holds pointers to char, which can be the first element of a string is irrelevant to how the array works. You need to understand the pointer to char as a string and array concepts separately, then combine them without mixing them …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Have you considered running Fedora in a VM? If all you need is a *nix system for the shell programming class, that strikes me as the better option than completely wiping your laptop and installing an OS that you may not use for longer than a few months.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm assuming that clever replacements for string.Split() are off the table too. Try looping over the characters in the string and print a newline when you reach whitespace:

foreach (char c in s)
{
    if (!char.IsWhiteSpace(c))
    {
        Console.Write(c);
    }
    else
    {
        Console.WriteLine();
    }
}

That's the simplest approach, but it makes some pretty big assumptions such as there won't ever be multiple adjacent whitespace characters. If that's the case, you need to take that into account and only print one newline for each span of whitespace. But the above should get you started.

tux4life commented: Cookie time :) +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

1) Leave the explanation of what a function does outside the function, and the comments about how it is done inside the function, near the code that does it.

I'd go even further (since I'm a sparse commenter) and say that comments should be limited to the following (examples taken from here, and recognizing that there's some redundancy with your recommendations):

  • Do comment why the code is there and why it works. This can be a business-level explanation of the problem that's being solved or a summary of the following block of code that saves the reader the trouble of deciphering what's happening and making an assumption about the intended purpose. Two examples:

    /* Strip leading whitespace */
    while (isspace(*it))
        ++it;
    
    /* Check for an integer part sign */
    if (*it == '-' || *it == '+')
        sign = (*it++ == '-');
    

    Notice how the code is reasonably clear without the comments, but the comments really nail down what the author was doing with each block.

  • Do comment how the code is intended to be used. This is in reference to things like Doxygen comments that are useful in generating documentation as well as providing code-level documentation.

  • Do include things that are going through your mind as you write the code. The reader won't necessarily be as intimate as you are with the problem and the solution, so there may be confusion if you're not expressing it. Two examples of comments that highlight what …

tux4life commented: Redundancy doesn't hurt in the case of good advice ;) +13
bguild commented: Vertical space is a valuable resource +6
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

-payroll system, inventory system, accounting system

Inventory is easy, accounting and payroll are quite a bit harder.

I want it to be like a web database

For payroll and accounting? No offense, but that's a really bad idea. An intranet portal is fine, but making it web accessible would be the height of stupidity, in my opinion.

Please give me professional idea, my idea is newbie ^_^

If this is for professional use, I'd highly recommend buying an existing package for each use. They'll be more mature and far less likely to fuck things up than a custom solution.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I bet Southerners get really cheesed off being referred to as 'Yanks' too.

Not especially, at least in my case. Then again, I tend to be apathetic about such things in general. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I've needed to write sample code using conio.h over the years, but my compilers don't support all of it (most notable being clrscr() and gotoxy()). So I wrote a conio simulator class to help me. Not all of the conio.h functions are present, such as cgets() and cscanf(), because I haven't needed them. But the design is such that they can easily be added.

It's based around an abstract IConio class that can be inherited from for specific implementations. The conio.h library is very platform specific, and I've included a Win32 implementation as I work primarily with Windows systems. POSIX implementations aren't especially difficult, but I don't have the confidence in writing something I'd want to show off. ;)

Here's an example program based on one of the samples I wrote recently:

#include <iostream>
#include <string>
#include <Windows.h>
#include "coniolib_win32.h"

namespace {
    const console::IConio& conio = console::Win32Conio();

    enum {
        KEY_ENTER = 13,
        KEY_ESC   = 27,
        KEY_UP    = 256 + 72,
        KEY_DOWN  = 256 + 80,
        KEY_LEFT  = 256 + 75,
        KEY_RIGHT = 256 + 77
    };

    enum {
        HILITE_SELECTED   = 433,
        HILITE_UNSELECTED = 23
    };

    int get_key(void)
    {
        int ch = conio.getch();

        if (ch == 0 || ch == 224) {
            ch = 256 + conio.getch();
        }

        return ch;
    }
}

int menu(int selected_row = 1)
{
    const int size = 3;
    const std::string rows[size] = {
        "1) Option 1",
        "2) Option 2",
        "3) Option 3"
    };

    conio.clrscr();

    if (selected_row < 1) {
        selected_row = 1;
    }

    if (selected_row …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

And this is why i am not being able to decide, what would attract audience the most..

Honestly, were I visiting a university and attending a presentation, I'd be more impressed with a solid project/presentation than an attractive or exciting project/presentation. The biggest problem I've seen with folks coming into the field from college is an almost universal inability to get things done. On the job training and experience fixes the problem quickly, but if you can show these CEOs that you can get things done, they'll be impressed regardless of the actual technical content.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I just want to send a word from my mobile as signal to my pc to do other task...

You have a number of options in this case, assuming a smartphone. The most general would be simple HTTP where the PC hosts a web service and the mobile connects to it. You could probably also use SMS, but I'm not very familiar with the protocol. If you want to communicate wired instead of wirelessly, how to go about it kind of depends on what the mobile supports in terms of connections and protocols through those connections.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Rather than try to decipher and work with that mess, I'll give you an example of what I think you're asking for:

#include <iostream>
#include <string>
#include <Windows.h>
#include "coniolib.h"

namespace {
    win32::ConioLib conio;

    enum {
        KEY_ENTER = 13,
        KEY_ESC   = 27,
        KEY_UP    = 256 + 72,
        KEY_DOWN  = 256 + 80,
        KEY_LEFT  = 256 + 75,
        KEY_RIGHT = 256 + 77
    };

    enum {
        HILITE_SELECTED   = 433,
        HILITE_UNSELECTED = 23
    };

    int get_key(void)
    {
        int ch = conio.getch();

        if (ch == 0 || ch == 224) {
            ch = 256 + conio.getch();
        }

        return ch;
    }
}

int menu(int selected_row = 1)
{
    const int size = 3;
    const std::string rows[size] = {
        "1) Option 1",
        "2) Option 2",
        "3) Option 3"
    };

    conio.clrscr();

    if (selected_row < 1) {
        selected_row = 1;
    }

    if (selected_row > size) {
        selected_row = size;
    }

    for (int i = 0; i < size; i++) {
        if (i + 1 == selected_row) {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), HILITE_SELECTED);
        }

        std::cout << rows[i] << '\n';

        if (i + 1 == selected_row) {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), HILITE_UNSELECTED);
        }
    }

    std::cout.flush();

    return selected_row;
}

void execute_selection(int selection)
{
    std::cout << "You selected option " << selection << '\n';
}

int main()
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), HILITE_UNSELECTED);

    int selected_row = menu(1);
    bool done = false;

    while (!done) {
        Sleep(100);

        if (conio.kbhit()) {
            switch (get_key()) {
            case KEY_UP:
                selected_row = selected_row > 1 ? selected_row - 1 : selected_row;
                menu(selected_row);
                break;
            case KEY_DOWN:
                selected_row = selected_row < 3 ? selected_row + 1 : selected_row; …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is it going to be possible to have a connection if I create a J2ME (netbeans) as client and vb.net (2010) as the server?

Provided they both use a compatible connection method, yes. In some cases you might also need to massage the data to and from what the server expects. This is usually the case when endianness comes into play where it's different on the client than the server.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Reverse the loop to count down from 100:

for (int i = 100; i >= 5; i -= 5) {
    System.out.print(i);

    if (i > 5) {
        System.out.print(",");
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

"It's not working" is completely useless. Describe how it's not working if you want better help. But I'll point out some obvious flaws in the code:

for (int i = 5 < = 100; 1 + = 5){

This line is all borked up. A for loop has three clauses separated by a semicolon and you only have one semicolon rather than two. <= is a single operator, and whitespace between the two parts will cause a syntax error. += is a single operator, separating whitespace won't work. 1 += 5 is nonsensical, you probably meant i += 5. The line should look like this:

for (int i = 5; i <= 100; i += 5) {
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There's no need to be so blunt or arrogant; well that is how you are coming across to me anyway.

I get progressively more annoyed when it seems like my advice is being ignored for no good reason.

Maybe that should have been 'What ELSE would you suggest?'

Make Shoe comparable in that it has an overloaded operator<, then use std::sort() from <algorithm>. Better yet, dump Shoe_List altogether and use std::list<Shoe>.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How can I grow the size of a char array?

That's easy, you can't. Arrays are statically sized and never change. If you want a dynamic array, you'll need to either simulate an array using pointers and dynamic allocation, or switch to a class that does it for you like std::vector.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, but each horse has a different odd of winning.

That's completely irrelevant to how you store the number of wins.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

a = here*;

This isn't valid syntax.

and in the function I check if here is NULL or not

You're not checking if here is NULL, you're checking if here->key is NULL. here->key is a char, so the test is nonsensical given that one of the operands is not a pointer. If here is NULL then trying to access key will result in an access violation. You want to do this:

if (here == NULL)
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'd use an array where the index represents the horse and the value stored at that index is the number of wins:

int wins[9] = {0};

// Simulate 100 races with each horse having equal probability of winning
for (int i = 0; i < 100; i++) {
    ++wins[rand() % 9];
}

// Display the formatted results
puts("Horse\tWins");

for (int i = 0; i < 9; i++) {
    printf("%d\t%d\n", i + 1, wins[i]);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What is the difference between CDbl() and Convert.ToDouble().

CDbl() is a little smarter by default in that it takes different numbering styles into consideration. You can get a similar effect with Double.Parse() and a formatter of NumberStyles.Any, with the understanding that the extra work has a runtime cost compared to Convert.ToDouble(), where the default behavior uses Double.Parse() with the less thorough NumberStyles.Float and NumberStyles.AllowThousands (if I recall correctly, of course. AllowThousands may not be default).

Ultimately it comes down to whether you want support for currency formatting, slightly more concise syntax, and don't mind depending on the Microsoft.VisualBasic assembly.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In lines 11 and 15 you're assigning to $count, not comparing it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how difficult would it be to have a .lib and a .dll file so I can work with both Linux/Unix and Windows?

You'd have two builds for the two systems. Whether the actual code that gets built needs to be ported to support the different systems depends on what you're doing. That also dictates how hard it is, but it could be as simple as just rebuilding with a different target (if the code is 100% standard C++, which is portable) to anywhere as hard as rewriting the whole thing (if you use a lot of platform dependent code).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

GIMP is the open source equivalent to Photoshop, but don't expect it to be as user friendly. I'm not familiar with the latest HTML packages. try searching Google. I use NetBeans if you're interested, though it's more of an IDE for PHP than a website designer like Dreamweaver.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Anyone know how to do it that way?

Unless you feel like dropping down to inline assembly, the best (only) solution is to verify that the operation won't overflow before you perform it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

My random number implementations in this program are not ment to be cryptographically secure.

I wasn't talking about being cryptographically secure. In fact, being cryptographically secure when all you need is something a user would recognize as "random" would be unnecessarily inefficient.

As an example of using the low order bits to generate a random sequence, there have been implementations where rand() % 2 would produce a range of [0,1,0,1,0,1,0,1...] (just alternating 0 and 1). This is a highly predictable and nobody would call it random. The low order bits of the result were disturbingly non-random, so using modulo to extract just those bits was a poor solution.

I would definitely pass and check the buffer size to the function. The dtoa function as given could easily overflow the buffer and not know it.

That code was taken from one of my libraries where I control the buffer, so it's guaranteed to be large enough for any double value. I don't think overflow is a huge issue when the string representation is tightly bound to an upper limit, and there was little point in adding it for this example as it distracts from the topic, but as a general library you're correct that it should account for being called by a moron. ;)

Also, I am using char (ASCII) and not wchar (Unicode). I do not plan on changing this, although the number adjustments could be a good idea.

I didn't assume otherwise in …

tux4life commented: Nothing would prevent a moron to pass a wrong buffer size though :D +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If the type is unknown, try using Object^. Provided you're working with CLI types, they're all derived from Object.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I wrote code to do this calculation but I can't find it, so I'll leave implementation as "an exercise for the reader". Have fun!

Piece of cake considering I've already written this for my standard C library implementation. Here's the meat of it, slightly modified:

#include <stdio.h>

#define _LEAP_YEAR(year)  (((year) > 0) && !((year) % 4) && (((year) % 100) || !((year) % 400)))
#define _LEAP_COUNT(year) ((((year) - 1) / 4) - (((year) - 1) / 100) + (((year) - 1) / 400))

const int yeardays[2][13] = {
    { -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 },
    { -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }
};

const int monthdays[2][13] = {
    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
    { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};

int weekday(int year, int month, int day)
{
    int ydays, mdays, base_dow;

    /* Correct out of range months by shifting them into range (in the same year) */
    month = (month < 1) ? 1 : month;
    month = (month > 12) ? 12 : month;

    mdays = monthdays[_LEAP_YEAR(year)][month - 1];

    /* Correct out of range days by shifting them into range (in the same month) */
    day = (day < 1) ? 1 : day;
    day = (day > mdays) ? mdays : day;

    /* Find the number of days up to the requested date */
    ydays = yeardays[_LEAP_YEAR(year)][month - 1] + day;

    /* Find the day of the week for January 1st */
    base_dow = (year * 365 + _LEAP_COUNT(year)) % 7;

    return (base_dow + ydays) % 7;
}

Dates are tricky though, and this only works within the confines of ISO C library requirements.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i guess ubuntu does not like finding rogue semicolons in the code for you.

This is a perfectly legal loop:

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

The compiler shouldn't diagnose it as an error, but can (and likely will) optimize it into this:

i = 20;

By the way, Ubuntu is an operating system, not a compiler. You probably mean GCC.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I would ask a few questions:

  1. "31 32 33..... til end of file". What does end of file mean here? Are you reading input from a file? Are you just printing numbers until the user tells you to stop? The behavior isn't obvious here, so writing code for it is impossible.

  2. How are negative values handled? Is it just assumed that all numbers are positive?

  3. What about things like ",," or ",-,"? Are they errors or need to be included in the logic?

Excluding the part that's completely ambiguous, and assuming only positive numbers, the rest of the logic is straightforward. However, dong it right doesn't result in teeny tiny code unless you're trying to obfuscate:

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

void print_range(int start, int stop)
{
    if (start > stop) {
        /* Print a decreasing range */
        while (start >= stop) {
            printf("%d ", start--);
        }
    }
    else {
        /* Print an increasing range */
        while (start <= stop) {
            printf("%d ", start++);
        }
    }
}

int main(void)
{
    int next; /* Represents the next character from the stream */

    do {
        char buf[BUFSIZ] = {0};

        /* Look for non-negative numbers */
        int rc = scanf("%[0123456789]", buf);
        int start = atoi(buf);

        next = getchar();

        if (next == '-') {
            int stop;

            if (scanf("%d", &stop) != 1) {
                /* Placeholder for ranges with an implicit end. Just error for now */
                fprintf(stderr, "Invalid  format: Missing range end\n");
                break;
            }

            print_range(start, stop);
            putchar('\n');

            next = getchar();
        }
        else if (next …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@deceptikon can you please explain the printf statement?

This is the point where I'll suggest that you RTFM, because format strings are clearly and completely described. But, I'll also explain it.

The %g specifier selects the behavior of either the %f or %e specifier (that's fixed or scientific format, respectively), depending on the actual value being printed. By default, if the exponent in your value exceeds 6 or -4, %g uses scientific format rather than fixed format. Trailing zeros are omitted, which is behavior you want (%f doesn't provide this).

When you provide a precision to the specifier (a dot followed by a numeric value), %g treats that as a maximum number of significant digits, which means both whole number digits and precision digits. For example, the value 123.456 has six significant digits. IF you try to print it with printf("%.4g", 123.456), you'll get 123.4 as output.

The numeric value in the precision can be a placeholder for an argument rather than a literal value in the string, that's what the asterisk does. It says "take the next argument to printf() and use that value as the precision". Another way of writing the example above using a placeholder would be printf("%.*g", 4, 123.456).

All in all, what my example does is calculate the number of digits in the whole value, then adds 8 to this (where 8 corresponds to the number of precision digits you want), then uses that value as the significant digits for the %g specifier. …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Haha we both typed almost identical instructions at the same time!

Great minds. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Pay special attention to the "precision" and "field width" specs above.

No disrespect, but unless I'm misreading your post (in which case I apologise) you should follow your own advice. ;) The %f specifier doesn't remove trailing zeros when the precision exceeds the value, and the precision on the %g specifier affects significant digits rather than digits after the radix. So while %g can be used to get the correct behavior, that's only after doing introspection on the value to determine how many whole digits are present:

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

int main(void)
{
    double a = 1234.567891234;

    // Quick and dirty digit count
    int digits = log10((double)(int)a) + 1;

    printf("%.*g\n", 8 + digits, a);

    return 0;
}
rubberman commented: Good point - haven't had to deal with this cruft in 20 years! :-) +11
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'd like to know if I'm doing the allocation of memory from data to new_data correctly

Looks like it, at least if set is implemented the way I'd implement it using that interface.

why new_data only has one value since the memory of data was copied before to new_data.

new_data is a pointer to a single integer, why would there be more than one value? Your question suggests that my assumptions about how your set is implemented are wrong and you're potentially leaking memory.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's no longer embedded in the post, but the file is still attached. You can remove it entirely through the same process that you added it:

  1. Edit the post
  2. Click the Files button
  3. Click the 'Delete' link next to the attached image (where the embed buttons are)
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yup, it's pretty simple:

I didn't suggest otherwise. It's a smidge more complicated because we'd still want to support local avatars, but I'd almost call such a feature trivial to implement...almost. ;)

My concern had more to do with whether supporting Gravatar would be both sufficiently beneficial as well as likely to continue to be beneficial going forward.

cereal commented: agree :) +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For starters, movie_rent is neither an object nor an array, it's a type. The object declaration would be more correct like this:

struct {
    char name[20];
    char year[20];
    int inout[20];
} movie_rent[20];

But that doesn't fix your syntax issues because you can't seem to decide if movie_rent is an array and inout is an int (circa line 30 and 34):

movie_rent[i].inout=0;

...

fscanf(myfile,"%c %c %d[^\n]", movie_rent[i].name, movie_rent[i].year,movie_rent[i].inout );

Or movie_rent is a single structure instance and inout is an array of int (line 39):

sum=sum+movie_rent.inout[i];

I suspect you want an array of movies:

#include <stdio.h>

int main(void)
{
    struct rental {
        char name[20];
        int year;
        int inout;
    } movies[20];

    FILE *in = fopen("mov.txt", "r");

    if (in) {
        size_t i, n, sum = 0;

        for (n = 0; n < 20; n++) {
            if (fscanf(in, "%19s %d %d", movies[n].name, movies[n].year, movies[n].inout) != 3) {
                break;
            }
        }

        fclose(in);

        for (i = 0; i < n; i++) {
            sum += movies[i].inout;
        }

        printf("Available movie count: %d\n", sum);
    }

    return 0;
}

This should work for movies that have a single word name (it's untested, so I reserve the right to have made stupid errors/typos), but for multiword names you're SOL using the %s specifier and need to figure out something different. I'd suggest flipping the format around so that the name is last, then doing this:

if (fscanf(in, "%d %d %19[^\n]", movies[n].name, movies[n].year, movies[n].inout) != 3) {
    break;
}

That way you …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Let's start with your assumption about the formatting of a numeric value, which isn't safe these days. Consider the following function that's designed to be locale-friendly for the same task:

#include <ctype.h>
#include <locale.h>
#include <math.h>
#include <string.h>

char *dtoa(char buf[], double value, int precision, int show_sign)
{
    char *grouping = localeconv()->grouping;   /* Locale-specific grouping count/order */
    int group_size = *grouping;                /* Current working group total size */
    int group_len = 0;                         /* Current working group processed size */
    double ipart;                              /* Integral half of the value */
    double fpart = modf(fabs(value), &ipart);  /* Fractional half of the value */
    size_t last = 0;

    /* Set and skip any explicit sign */
    if (value < 0 || show_sign) {
        buf[last++] = (value < 0) ? '-' : '+';
    }

    /* Build the locale-friendly integer part */
    for (; fabs(ipart) > 1; ipart /= 10) {
        if (group_size && group_len++ == group_size) {
            /*
                The current working group has been completed. Apply
                a group separator and move to the next locale-specified 
                grouping. Repeat the last valid grouping if the locale
                doesn't specify any further groupings.
            */
            buf[last++] = *localeconv()->thousands_sep;

            if (*grouping && *++grouping) {
                group_size = *grouping;
            }

            /* Reset the group to 1 because a digit is still being processed */
            group_len = 1;
        }

        buf[last++] = (char)(fmod(ipart, 10) + '0');
    }

    if (last == 0 || (last == 1 && !isdigit(buf[0]))) {
        /* There weren't any integer part digits, force to 0 */
        buf[last++] = (char)((int)fmod(ipart, 10) + …