Narue 5,707 Bad Cop Team Colleague

>but what about the order of the operators?
What about them?

Narue 5,707 Bad Cop Team Colleague

>why it's so?
Enter is a character too, the newline ('\n'). On your system it has a value of 10, so 10 - 48 = -38. Note that your condition fails to catch the newline because you've already changed the value by that time.

Narue 5,707 Bad Cop Team Colleague

>I mean - read the characters coming from keyboard
Yes, I assumed that's what you meant by "input stream of the console". How does my answer not apply?

Narue 5,707 Bad Cop Team Colleague

Read characters until a newline or EOF is reached:

int ch;

do
    ch = getchar();
while (ch != '\n' && ch != EOF);

This is the only portable method, but it also has a downside of blocking for input if the stream is already empty when the loop starts. Unfortunately, there's no way to get around that without breaking portability.

vedro-compota commented: +++ +1
Narue 5,707 Bad Cop Team Colleague

>Wow! I'm getting the correct answer now!
...

frogboy77 commented: We get it, you're great; because "they" said you couldn't be. +0
Narue 5,707 Bad Cop Team Colleague

>Is there any way I can prevent this copy?
No, not really. In calling operator<<, you've bound the temporary object to a reference, which basically invalidates it for further copy elimination.

>had I known that it would make copies all the time I would not have done it...
It's best to assume that at least one copy of an exception object will be made when throwing.

Narue 5,707 Bad Cop Team Colleague

Actually, endianness is irrelevant here. The logical behavior of shifting is the same regardless of how the underlying values are actually stored.

Fbody commented: good to know. :) +5
Narue 5,707 Bad Cop Team Colleague

Your thinking is backward. Try left shifting instead of right shifting.

Narue 5,707 Bad Cop Team Colleague

You're missing a terminating semicolon on the Classic class.

Narue 5,707 Bad Cop Team Colleague

I have a better idea. How about you show us your attempts at writing functions and we can show you where you went wrong? Otherwise you're essentially asking for a full tutorial on how to write functions, which most of us aren't inclined to write.

Narue 5,707 Bad Cop Team Colleague

When writing a library you need to take care to only make the names that should be visible to client code extern; the rest should be static for file visibility. Names that are extern should be designed to avoid clashing with client code and other libraries as well. Finally, any objects and functions should only be declared in your header, then defined in a separate definition file to avoid multiple definitions if the header is included more than once. For example:

/* mymalloc.h */
#ifndef MYMALLOC_H
#define MYMALLOC_H

#include <stddef.h>

/* Declaration only for variable */
extern int mymalloc_use_freelist;

/* Declarations only */
extern void *mymalloc(size_t bytes);
extern void myfree(void *p);

#endif
/* mymalloc.c */
#include <mymalloc.h>
#include <mylist.h>

/* Not visible to the outside */
static mylist *freelist = NULL;

/* Definition for extern variable */
int mymalloc_use_freelist = 0;

/* Not visible to the outside, internal helper only */
static void *more_core(size_t bytes)
{
    /* ... */
}

/* extern function declarations */
void *mymalloc(size_t bytes)
{
    /* ... */
}

void myfree(void *p)
{
    /* ... */
}

Macro names can be an issue, but if they're intended for internal use only, you can #undef them at the end of the file.

Narue 5,707 Bad Cop Team Colleague

>I can't read this program because I'm using C++
The code I posted is C++.

>Is this write [sic] ??
Yes.

Narue 5,707 Bad Cop Team Colleague

You're accessing the array out of bounds. In main, index exceeds 999, which is the largest available index in primes. Anything can happen, including wacky output and crashes.

Narue 5,707 Bad Cop Team Colleague

I'm feeling generous today, so here's an example. Note that it doesn't use files, and the standard library is used for brevity, but all of the requisite logic is in place for the avail_list. You should have no trouble figuring out what I did and why. If not, feel free to ask and I'll be happy to explain any details:

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

enum menu_opt {
    ADD_RECORD,
    DELETE_RECORD,
    PRINT_RECORDS,
    EXIT
};

menu_opt menu()
{
    std::cout<<"1) Add Record\n2) Delete Record\n3) Print Records\n4) Exit\n> ";

    std::string opt;

    while (getline(std::cin, opt)) {
        if (opt.empty())
            continue;

        switch (opt[0]) {
        case '1': return ADD_RECORD;
        case '2': return DELETE_RECORD;
        case '3': return PRINT_RECORDS;
        case '4': return EXIT;
        default:
            std::cout<<"Invalid option. Please try again> ";
        }
    }

    return EXIT;
}

int main()
{
    // Records are a simple string, for simplicity
    typedef std::vector<std::string> record_list_t;

    // The avail_list acts as a queue, so the first deleted index
    // is the first index used when adding new records
    typedef std::deque<record_list_t::size_type> avail_list_t;

    record_list_t records;
    avail_list_t avail;
    std::string record;
    menu_opt opt;

    while ((opt = menu()) != EXIT) {
        switch (opt) {
        case ADD_RECORD:
            std::cout<<"Search Key> ";

            if (getline(std::cin, record)) {
                // Check for deleted indices
                if (avail.empty())
                    records.push_back(record);
                else {
                    // Use the first available index
                    records[avail.back()] = record;

                    // Mark the index as used by removing it
                    avail.pop_back();
                }
            }

            break;
        case DELETE_RECORD:
            std::cout<<"Search Key> ";

            if (getline(std::cin, record)) {
                for (record_list_t::size_type i = 0; i < records.size(); i++) {
                    if (records[i] …
Narue 5,707 Bad Cop Team Colleague

>scanf("%s",&fnamen);
fnamen is already a pointer in this context. Adding a redundant address-of operator changes the type, which can potentially break your program (though it's usually benign in this case).

Also consider that %s without a field width is no better than gets (ie. there's no protection from buffer overflow), and the result of scanf should be tested for failure:

if (scanf("%11s", fnamen) != 1) {
    fputs("Invalid input\n", stderr);
    exit(EXIT_FAILURE);
}

>char fnamew[100]="";
I'd also like to point out that initializing fnamew to an empty string is absolutely critical if you're going to immediately call strcat, because strcat expects to be given a valid string. The following is broken because fnamew isn't a valid string (no null terminator):

char fnamew[100];
char dpath[50]="C:\\TC\\BIN\\GIFS\\";

strcat(fnamew,dpath);

Because of this subtlety, I often recommend using strcpy to populate the initial portion of the string, then strcat to append. Then it doesn't matter what the destination's current contents happen to be:

strcpy(fnamew,dpath);
strcat(fnamew,fnamen);
strcat(fnamew,ext);
Narue 5,707 Bad Cop Team Colleague

>should i sort it??
It doesn't matter. I'd recommend keeping things simple until you have a working draft of the availability list.

>and i want to mark the record as deleted what should i use??
You don't need to mark the record as deleted. The presence of the search key/index in your avail_list serves that purpose.

Now for some advice. You're not going to learn jack until you take some chances, screw shit up, and get out of holes you dig for yourself. Your questions reek of fear. You're afraid of doing things the "wrong" way, or making mistakes, or having to start over from scratch because you made a poor decision in the beginning. But all of those are necessary to grow. The only way to get really good at this stuff is experience, and experience is nothing more than a mountain of mistakes. Don't expect people to hold your hand, because it's not going to happen, and it wouldn't help you in the long run anyway.

Narue 5,707 Bad Cop Team Colleague

How about storing the record index in your avail_list? If it's in the avail_list, clearly it doesn't have a legit record and whatever data is there can be overwritten.

Narue 5,707 Bad Cop Team Colleague

>fillnumb will be =2
Why would it be? If fillnumb is 0, then that falls into your case 0, which sets fillnumb to 1. A break at the end of a case terminates the switch statement, so execution won't fall through to case 1.

Narue 5,707 Bad Cop Team Colleague

It depends on the type and scope of the variable. Can you be more specific?

vedro-compota commented: +++ +1
Narue 5,707 Bad Cop Team Colleague

>how can i khow which index is empty and when the empty indexs are
>finish and when to start adding data at the append of index file

That's what the avail_list is. It's a separate array/list of available indices. When a record is deleted, its index is added to the avail_list. When a new record is added, first search the avail_list for the next available index. If there's an available index, remove it from the avail_list and insert the record. Otherwise append the record.

Narue 5,707 Bad Cop Team Colleague

Use a loop:

if (argc > 1) {
    int i;

    for (i = 1; i < argc; i++) {
        /* Open and read argv[i] */
    }
}
Narue 5,707 Bad Cop Team Colleague

>__func__ returns current function but I need caller function.
Did it occur to you to pass the result of __func__ to the called function? The result you want can be had fairly easily, but you'll need to compromise a little. There's not a simple and fast way to get the calling function name from within the called function without some kind of scaffolding in place.

Narue 5,707 Bad Cop Team Colleague

Let's say you have an array {a, b, c, d, e} . Now c is deleted resulting in {a, b, (empty), d, e} . The avail_list logic would store index 2 such that adding a new item (f) would result in {a, b, f, d, e} rather than {a, b, (empty), d, e, f} . So f is added to index 2 (the first empty slot) instead of to a new index 5.

Narue 5,707 Bad Cop Team Colleague

C99 added __func__, which evaluates to the name of the currently executing function. __FUNCTION__ is a common non-standard extension that does the basically same thing.

Narue 5,707 Bad Cop Team Colleague

char is a keyword, you can't use it for a variable name. And don't use magic numbers. If you must rely on ASCII (std::tolower exists for a reason), at least use character literals:

if (c >= 'A' && c <= 'Z')
    c += 'a' - 'A';
Narue 5,707 Bad Cop Team Colleague

>Thank you for your generally unproductive post
Thank you for wasting everyone's time by not asking a smart question. I'm glad you solved your problem though.

Narue 5,707 Bad Cop Team Colleague

>It means there's some problem with my codeblocks
Why do people always assume it's the compiler? 99.9% of the time the problem is with your code, or your assumptions.

Narue 5,707 Bad Cop Team Colleague

Alright then, since this is clearly reliant on input, please post some sample inputs that fail to produce output. This is a stupid question, but you are entering input such that the first loop terminates, right?

>Which compiler did you use?
Visual Studio 2010 and Pelles C.

Narue 5,707 Bad Cop Team Colleague

Can you post a complete program that exhibits the problem? Troubleshooting through snippets is generally unproductive.

Narue 5,707 Bad Cop Team Colleague

I'm getting correct output for simple test cases. Perhaps you mean the output window is closing before you can see the results? If that's so, add a call to getchar just before returning from main:

int main()
{
    int a[20],n,ctr=0,j=0;
    printf("\nEnter number of elements:");
    scanf("%d",&n);
    printf("Enter array elements:");
    while(ctr<n)
    {
        scanf("%d ",&a[ctr]);
        ctr++;
    }
    Quick_sort(a,0,n-1);
    printf("\nSorted Array:");
    while(j<n)
    {
        printf("%d ",a[j]);
        j++;
    }
    getchar();
    return 0;
}
Narue 5,707 Bad Cop Team Colleague

Can you post a main function that does absolutely nothing except present the issue? To be perfectly honest, it's too much effort to paste your code into a project and then divine what inputs are required to make it "not work".

Narue 5,707 Bad Cop Team Colleague

This may be helpful. I think the real problem here is you're not seeding rand properly and expecting the default seed to be different each time (which it's not).

Narue 5,707 Bad Cop Team Colleague

I see a major discrepancy in your use of the input variable. Is it a char, or an array of char? Because either way you're misusing it somewhere.

Narue 5,707 Bad Cop Team Colleague

The %[] specifier is a scan set. scanf will look for everything between the brackets and act accordingly. If the scan set begins with a ^ character, it means to exclude the characters in the scan set, otherwise include them. So %[^\n] means to read and store everything up to a newline in the corresponding string parameter. You can use the same trick to stop at a comma: %[^,] , but keep in mind that the delimiting character is not extracted, so you need to remove it manually by using a literal in the format string:

#include <stdio.h>

int main(void)
{
    unsigned long id;
    char last_name[10];
    char first_name[10];

    while (scanf("%d %[^,], %[^\n]", &id, last_name, first_name) == 3)
        printf(">%s< >%s<: %d\n", first_name, last_name, id);

    return 0;
}
Narue 5,707 Bad Cop Team Colleague

Just fill the buffer back up and use the resulting count. The previous contents will be overwritten:

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

int main(void)
{
    FILE *in = fopen("test.txt", "r");
    char buffer[10];
    size_t n;

    if (in == NULL) {
        perror(NULL);
        return EXIT_FAILURE;
    }

    while ((n = fread(buffer, 1, sizeof buffer, in)) > 0)
        fwrite(buffer, 1, n, stdout);

    fclose(in);

    return 0;
}
moroccanplaya commented: genius thats what all im going to say, shes my life saver +1
Narue 5,707 Bad Cop Team Colleague

>Is there any drawbacks for using "this" pointer?
It's harder to read and more work to type?

>Is it a good practice to use "this" all the time and whenever possible?
When it comes to this particular usage, I think this should be avoided except to resolve an ambiguity. However, it's a style issue. If you want to add a redundant this-> to everything, feel free.

Narue 5,707 Bad Cop Team Colleague

Short answer: cout is interpreting the object as a bool due to the volatile qualifier. It's a quirk of overloading for the << operator.

Long answer: A volatile pointer can't be converted to a non-volatile pointer without an explicit cast, so neither the char* nor the void* overload can be used when the << operator is called. There's no volatile qualified overload, and the closest match is the bool overload, thus your array is interpreted as a boolean value rather than an address or a string.

You can fix it a number of ways, but an explicit cast is probably what you wanted:

std::cout<< (char*)str <<std::endl;

p.s. While your compiler may set uninitialized variables to 0 automatically, it's a very bad idea to rely on that behavior because it's not universal. So in your loop, int i; should be int i = 0; .

Narue 5,707 Bad Cop Team Colleague

Assuming we're talking about a std::string object and not a pointer to char:

stringstream ss;

ss<<"CASH WITHDRAWAL "<< safe_input2 <<" GBP";
data[person].history[data[person].trans] = ss.str();
Narue 5,707 Bad Cop Team Colleague

Yes, you can buy motherboards that have multiple CPU slots. How do you think we managed multiple cores before multi-core processors came out? ;)

cwarn23 commented: Excellent information and gr8 news for me! +6
Narue 5,707 Bad Cop Team Colleague

>Is this Program Correct? or is there more conditions to check..?
No and no, respectively. Your algorithm for the leap year condition is correct, but your code has a little to be desired.

>#include <conio.h>
This header is completely unnecessary for this program. I highly recommend you get out of the habit of including unnecessary non-portable libraries.

>void main(void)
main has returned int for about 60 years. It looks like this:

int main(void)
{
  /* Your code here */

  return 0;
}

Or if you're accepting command line parameters, this:

int main(int argc, char *argv[])
{
  /* Your code here */

  return 0;
}

Nothing else is acceptable if you're a beginner.

>clrscr();
I hate this for two reasons:

  1. clrscr is not a portable function, which means you've limited your code to the compiler that it was written with. Further, clrscr is unnecessary in this situation, so you've needlessly destroyed portability.
  2. Clearing the screen at the beginning of the program is either pointless or antisocial. If you're running the program from an IDE, the output window is owned by the IDE and nothing will precede your first explicit output anyway. If you're running from the command line, removing the entirety of output from previous programs will piss off damn near everyone who uses your program.

>printf("\n\n enter a year::");
While I'm sure it works fine on your compiler and system, output is only guaranteed to be displayed …

vinitmittal2008 commented: so helpful info :) +1
Narue 5,707 Bad Cop Team Colleague

>Thanks for the help, but I was doing it right
If you expected a reassignment of rootNode in AppendNode to change rootnode in main, you were doing it wrong.

>I did not think it was a coding error, looked more like compiler issue to me.
Only a fool blames the compiler first. Your code doesn't match your expectations. It's a misunderstanding of pointers, not a compiler issue.

>either way value of i and thus of *p and thus of **p is changing.
Yes! So you've got the basic concept down, now you need to apply it to pointers instead of integers. Instead of changing the value of i, change what p points to. I can guarantee that the only way you'll be able to manage it is by assigning to *pp. My second example illustrates what your code was doing with wrong(), and what your code should be doing with right().

hyperion commented: I am not really a fool, just caught with some oversight :D +4
Narue 5,707 Bad Cop Team Colleague

>How could a JFrame, an image file, a video file or a text file etc...
>be represented by only a bunch of 000000's and 1111111's?

0 and 1 are really just a convenient notation for the electrical pulses a binary computer uses to generate streams of data. Those pulses are interpreted by a chain of consumers which convert the bit stream back and forth between different representations.

How can something as complex as an image be represented by a stream of 0's and 1's? By combining them into an equally complex language suitable for consumption by a display driver which then determines which pixels on a monitor to light up. When you really think about the complexity of the whole system, it's a wonder that computers work at all.

>Is it good or bad to think this way for a first year student?
It's good to understand such low level things, but probably not until a solid base in more practical matters is built. Keep it on the back burner, but don't stress too much about pretending that some things work by "magic" until you're in a better position to learn how they really work.

islam-morad commented: Great post, Thanks +1
Narue 5,707 Bad Cop Team Colleague

>But even after AppendNode call, rootnode is NULL.
Yes, because any changes to rootnode within AppendNode will not persist back to main. In AppendNode, rootNode is a copy of the pointer, not a reference to it. I suspect you need more study on how pointers work between functions:

#include <stdio.h>

void foo(int *p, int **pp)
{
    printf("foo()\n\tp:   %p\n", (void*)&p);
    printf("\tpp:  %p\n", (void*)&pp);
    printf("\t*pp: %p\n", (void*)*pp);
}

int main()
{
    int i = 123;
    int *p = &i;
    int **pp = &p;

    printf("main()\n\tp:   %p\n", (void*)&p);
    printf("\tpp:  %p\n", (void*)&pp);
    printf("\t*pp: %p\n", (void*)*pp);
    foo(p, pp);

    return 0;
}

The way to pass a reference to an object in C is by passing a pointer to that object. Notice how the address of the pointer p in foo is different from the address of p in main. That's because foo's p is a copy of the pointer, a completely different object. If you change where p points to in foo, p in main doesn't change unless you pass a pointer to p (ie. pp), and modify the dereferenced object:

#include <stdio.h>

void wrong(int *p)
{
    p = NULL;
}

void right(int **p)
{
    *p = NULL;
}

int main()
{
    int i = 123;
    int *p = &i;
    
    printf("%snull\n", p == NULL ? "" : "NOT ");
    wrong(p);
    printf("%snull\n", p == NULL ? "" : "NOT ");
    right(&p);
    printf("%snull\n", p == NULL ? "" : "NOT ");

    return 0;
}
Narue 5,707 Bad Cop Team Colleague

>Private data members cannot be accessed outside the class.
Yes.

>When a class inherits a base class, all the data members except the private get inherited into it.
Private members are inherited, but not accessible from the child class.

>So if we want data members to be accessible to only derived classes
>and not privately or publicly accessible, then we can use protected.

While not incorrect, this answer is the kind of cookie cutter thing you'd get right out of a textbook. It shows knowledge, but not necessarily understanding.

A better answer would give a practical example for using protected, explain why it's preferred, then derive a more general guideline from the explanation. This covers all bases in that it shows you can think of a good situation where protected makes sense (understanding of the concept), defend the decision (understanding the pros and cons versus alternatives), and draw a logical conclusion (show creativity and independent thought).

Narue 5,707 Bad Cop Team Colleague

*sigh*

int a = 25;
wchar_t buf[80];

swprintf(buf, L"%d", a);
MessageBox(NULL, buf, L"Sel Change", MB_OK);
Narue 5,707 Bad Cop Team Colleague

The cast to a wide string type should raise red flags. Perhaps you should consider wchar_t and swprintf from the get-go instead of trying to drop narrow characters into wide holes and hoping for magic.

Narue 5,707 Bad Cop Team Colleague

>i would like to know more about the book before i buy it.
FYI, TAOCP consists of several volumes, and it's concentrated awesome. If I could only keep one of my books (I have many), it would be TAOCP (probably volume 3).

>Reviews as to how the Math in it is
Intense, but if you're not a math head you can still get a lot out of the books.

Narue 5,707 Bad Cop Team Colleague

Just one question, what were you expecting to happen with this?

for(int i=0; i<a.elements; i++)
    delete[] &a.element[i];

All you need to do is the inverse of what you did to allocate the memory:

void deallocate(GrowableArray &a)
{
    delete[] a.element;
}
Narue 5,707 Bad Cop Team Colleague

So the problem is something of a misunderstanding of C-style strings. I'd recommend not using read and write (in general, actually, because they're only safe for POD types) and read each data member individually:

//dat.read ((char *) &data, sizeof(data)); //should read data
dat.get(data.name, sizeof data.name);
dat.get(data.lastname, sizeof data.lastname);
Narue 5,707 Bad Cop Team Colleague

You need to compile GradeBook.cpp as well. Only headers need not be compiled:

g++ main.cpp GradeBook.cpp -o main