Narue 5,707 Bad Cop Team Colleague

I suspect they use several. Can you be more specific about which feature of facebook you're referring to?

Narue 5,707 Bad Cop Team Colleague

So, can you see what is wrong with the program?

I'd wager that it has something to do with your math. You're using the size of the buffer rather than the number of extracted characters to calculate the seek offset. Compare and contrast:

char *a3_fgets_2(char *str, int num, int fd)
{
    int n = read(fd, str, num - 1);
    int i = 0;
    
    if (n <= 0)
        return NULL;

    while (i < n) {
        if (str[i++] == '\n')
            break;
    }
    
    lseek(fd, i - n, SEEK_CUR);
    str[i] = '\0';

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

A pointer is not an array, it only plays one on television. You have to allocate memory to the pointer and then assign values, which for the purpose of this post we'll say you cannot do in a structure initialization list:

#include <iostream>
#include <string>

using namespace std;

struct sample {
    string name;
    double *num;
    unsigned elements;
};

int main ()
{
    sample x  = {"Dude", 0, 4};
    double init[] = {1, 2, 3, -5};
    
    x.num = new double[x.elements];
    
    for (int i = 0; i < x.elements; i++)
        x.num[i] = init[i];
    
    cout << x.name << '[' << x.elements << "]:\n";
    
    for (int i = 0; i < x.elements; i++)
        cout << '(' << x.num[i] << ")\n";
        
    delete[] x.num;
}
Narue 5,707 Bad Cop Team Colleague

0x1A is the ASCII value for Ctrl+Z, which is the end-of-file character for a text stream on Windows. Since you're doing arbitrary seeking on the file anyway (an operation that's undefined for text mode streams), you can open the file as binary and that will fix the problem of 0x1A as well:

myfile.open("D:\\test.gh", ios::in | ios::out | ios::binary);
Narue 5,707 Bad Cop Team Colleague

Done.

Narue 5,707 Bad Cop Team Colleague

So I don't think my do-while loop is right... I don't know how to keep shifting the structs down until the end though...

The idea is to pretend the record being deleted is a hole in the array and fill it in with everything after it:

// Find the record and store its index in i...

// Fill in the "hole" starting at i to delete stdRec[i]
for (int x = i; x < n - 1; x++)
    stdRec[x] = stdRec[x + 1];

// Decrement the length of the array to reflect the deletion
--n;
C++newbie chick commented: awesome! +1
Narue 5,707 Bad Cop Team Colleague

But I want to do with overloading

Then do it with overloading. It's completely redundant and unnecessary, but with the algorithm changes you'll get the same results:

#include <algorithm> // For fill() and reverse()
#include <iostream>

using namespace std;

class dec_to_bin {
    char bin[33];
public:
    char *to_bin(unsigned int value, int size);
    char *to_bin(unsigned short value, int size);
};

char *dec_to_bin::to_bin(unsigned value, int size)
{
    int i = 0;
    
    std::fill(bin, bin + sizeof bin, '\0');
    
    while (value != 0 && i < size) {
        bin[i++] = value % 2 + '0';
        value /= 2;
    }
    
    while (i < size)
        bin[i++] = '0';
    
    std::reverse(bin, bin + size);
    
    return bin;
}

char *dec_to_bin::to_bin(unsigned short value, int size)
{
    return to_bin((unsigned)value, size);
}

int main()
{
    dec_to_bin b;
    
    cout << "bin int:   " << b.to_bin(20U, 32) << '\n';
    cout << "bin short: " << b.to_bin((unsigned short)21, 16) << '\n';
}

If you had actually put some thought into this before rejecting my help, you'd have come to the same conclusion.

Narue 5,707 Bad Cop Team Colleague

How can I use same algorithm with different types of arguments?

That's like a leading question for templates. But you can actually do this without making a template by tweaking the algorithm slightly (more like simplifying it, actually):

#include <algorithm> // For fill() and reverse()
#include <iostream>

using namespace std;

class dec_to_bin {
    char bin[33];
public:
    char *to_bin(unsigned int value, int size);
};

char *dec_to_bin::to_bin(unsigned value, int size)
{
    int i = 0;
    
    std::fill(bin, bin + sizeof bin, '\0');
    
    while (value != 0 && i < size) {
        bin[i++] = value % 2 + '0';
        value /= 2;
    }
    
    while (i < size)
        bin[i++] = '0';
    
    std::reverse(bin, bin + size);
    
    return bin;
}

int main()
{
    dec_to_bin b;
    
    cout << "bin int:   " << b.to_bin(20, 32) << '\n';
    cout << "bin short: " << b.to_bin((unsigned short)21, 16) << '\n';
}

No overload is needed because smaller types will be promoted to the larger type. You might see some wierdness with a signed to unsigned conversion, but that's a problem for another day. Also a problem for another day is sanity checks such as making sure that size is within the bounds of unsigned int 's bit count.

Narue 5,707 Bad Cop Team Colleague

You forgot to add a comma between the parent name and age values:

cmdtext = "insert into tblSTUDENT(FULLNAME, PARENTNAME, AGE) VALUES('"
                + txtStudentName.Text + "',  '" + txtParentName.Text + "', " + txtAge.Text.ToString() +")";

Sometimes it helps to use string.Format() instead of concatenation because the formatting around placeholders is easier to see:

cmdtext = string.Format(
    "insert into tblSTUDENT(FULLNAME, PARENTNAME, AGE) VALUES ('{0}', '{1}', {2});",
    txtStudentName.Text,
    txtParentName.Text,
    txtAge.Text);
Narue 5,707 Bad Cop Team Colleague

But printing both(unsigned int and unsigned short), it prints unsigned int type.

Duh. Of course it has the same results because you use the same algorithm (and the same types) to generate the string.

Narue 5,707 Bad Cop Team Colleague

But its not working

Not helpful. How is it not working? What did you expect versus what it currently does?

Narue 5,707 Bad Cop Team Colleague
to_bin(dec,size); //using same function again

Yes, you're using the same function again. This is a recursive call with no base case, which means your error is a stack overflow. Try casting the arguments into an exact match for the overloaded function if you want to reuse it:

to_bin(static_cast<unsigned int>(dec), size); //using same function again
Narue 5,707 Bad Cop Team Colleague

You didn't fix the problem of accessing an array out of range. dest[55] is not a valid index, for example. It's also silly to declare an array and then only use one element. I think you need to study up a bit on arrays and how they work in C.

Narue 5,707 Bad Cop Team Colleague

My crystal ball says that it's due to always accessing the 99th index in arrays that only have room for 99 items (ie. the last valid index is 98).

Narue 5,707 Bad Cop Team Colleague

You'll want to read a full line, then break it down into columns with something like stringstream:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    std::ifstream in("test.txt");
    std::vector<std::vector<int> > v;
    
    if (in) {
        std::string line;
        
        while (std::getline(in, line)) {
            v.push_back(std::vector<int>());
            
            // Break down the row into column values
            std::stringstream split(line);
            int value;
            
            while (split >> value)
                v.back().push_back(value);
        }
    }
    
    for (int i = 0; i < v.size(); i++) {
        for (int j = 0; j < v[i].size(); j++)
            std::cout << v[i][j] << ' ';
            
        std::cout << '\n';
    }
}
Narue 5,707 Bad Cop Team Colleague

The = operator assigns while the == operator tests for equality. You're using the assignment operator for equality, and C's implicit equality rules apply. Here's an example of your code:

if (type = 1)
    bus[99] = "Single-decker";
else
    bus[99] = "Double-decker";

Here's how C is really interpreting it:

type = 1;

if (type != 0)
    bus[99] = "Single-decker";
else
    bus[99] = "Double-decker";

As you can see, that comparison will always be true because you ensure it with an assignment to 1 prior to making to comparison. The else clause will never be executed.

Narue 5,707 Bad Cop Team Colleague
redblacktree<int> *r;
r=rb.search(90);

It looks like exactly what the error states. rb.search() returns a pointer to T, not a pointer to redblacktree<T>. Since the code for redblacktree::search() really does return a pointer to redblacktree<T>, your member function signature is wrong. IT should be:

redblacktree<T>* search(T y) {
    ...
}

After this change the code compiles and runs to completion on my system, but I didn't check the results for correctness.

Narue 5,707 Bad Cop Team Colleague

The very definition of an abstract method in C# is a function declaration without an implementation. Non-abstract derived classes are required to provide the implementation. If you want to provide a default implementation, the method should be virtual rather than abstract.

If you want to keep it abstract just replace the body with a semicolon. That makes it a declaration rather than a definition:

public abstract Graphics drawRectangle(Graphics drawarea);
Narue 5,707 Bad Cop Team Colleague

I tried this way, but then it gives me error when I printf the count for integars in the FILE

Then your call to printf() was wrong, not the loop for building metrics. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

I don't see the need for nested loops here, just keep a running count:

while (fscanf(in, "%d", &number) == 1) {
    ++n;

    if (number % 2 == 0)
        ++even;
    else {
        sum += number;
        ++odd;
    }
}

/* Calculate the average... */

/* Display the results */
Narue 5,707 Bad Cop Team Colleague

Typo: q-left->parent=pu; should be q->left->parent=pu; . In an annoyance you'll encounter many times, the symmetric case has the same problem in the same place because you probably cut and pasted to get it.

Another line that raises red flags is this one:

while((q->parent->color=true)&&(q->color=true)) {

Did you intend to use assignment?

Narue 5,707 Bad Cop Team Colleague

The assignment operator doesn't play well with the insertion (<<) and extraction (>>) operators. Ideally you would break those expressions out and print the result:

meters = miles*YARDS_PER_MILE*INCHES_PER_YARD*METERS_PER_INCH;
meters2 = yards*INCHES_PER_YARD*METERS_PER_INCH;
meters3 = feet/FEET_PER_YARD*INCHES_PER_YARD*METERS_PER_INCH;
meters4 = inches*METERS_PER_INCH;
totalmeters=meters+meters2+meters3+meters4;
    
cout <<"Units\t\tValue\t\tMeters\n\n\n";
cout <<"Miles\t\t"<<miles<<"\t\t"<<meters<<"\n\n";
cout <<"Yards\t\t"<<yards<<"\t\t"<<meters2<<"\n\n";
cout <<"Feet\t\t"<<feet<<"\t\t"<<meters3<<"\n\n";
cout <<"Inches\t\t"<<inches<<"\t\t"<<meters4<<"\n\n\n";
cout <<"Total\t\t"<<"\t\t"<<totalmeters;

The simpler your individual statements are, the easier the code will be to read and understand. Alternatively you could remove the assignment entirely since you don't use the result object:

cout <<"Units\t\tValue\t\tMeters\n\n\n";
cout <<"Miles\t\t"<<miles<<"\t\t"<<miles*YARDS_PER_MILE*INCHES_PER_YARD*METERS_PER_INCH<<"\n\n";
cout <<"Yards\t\t"<<yards<<"\t\t"<<yards*INCHES_PER_YARD*METERS_PER_INCH<<"\n\n";
cout <<"Feet\t\t"<<feet<<"\t\t"<<feet/FEET_PER_YARD*INCHES_PER_YARD*METERS_PER_INCH<<"\n\n";
cout <<"Inches\t\t"<<inches<<"\t\t"<<inches*METERS_PER_INCH<<"\n\n\n";
cout <<"Total\t\t"<<"\t\t"<<meters+meters2+meters3+meters4;

Finally, you can correct the error by fixing the precedence with parentheses:

cout <<"Units\t\tValue\t\tMeters\n\n\n";
cout <<"Miles\t\t"<<miles<<"\t\t"<<(meters = miles*YARDS_PER_MILE*INCHES_PER_YARD*METERS_PER_INCH)<<"\n\n";
cout <<"Yards\t\t"<<yards<<"\t\t"<<(meters2 = yards*INCHES_PER_YARD*METERS_PER_INCH)<<"\n\n";
cout <<"Feet\t\t"<<feet<<"\t\t"<<(meters3 = feet/FEET_PER_YARD*INCHES_PER_YARD*METERS_PER_INCH)<<"\n\n";
cout <<"Inches\t\t"<<inches<<"\t\t"<<(meters4 = inches*METERS_PER_INCH)<<"\n\n\n";
cout <<"Total\t\t"<<"\t\t"<<(totalmeters=meters+meters2+meters3+meters4);
Aghtar commented: Thanks again Narue +1
Narue 5,707 Bad Cop Team Colleague

At the bottom of the thread (after the last post) you'll find a block of text:

Has this thread been answered?
If this thread has been successfully resolved, please Mark this Thread as Solved so that it can be added to our Knowledge Base and help others. Also, posters who replied appreciate knowing that they were helpful.

The "Mark this Thread as Solved" part is a link that will mark the thread as solved on the forum view.

Narue 5,707 Bad Cop Team Colleague

Assuming I understand your question, yes.

Narue 5,707 Bad Cop Team Colleague

yes i know tos determines the top of stack and i want an empty integer but i am not able to make that element empty, that's why i assigned 0 values to remaining array. Could you tell me how to make any element empty using nullable type?

I don't think you understand. You don't need to make that element empty. I suspect you think you need to make it empty because of the display() method, which is wrong. You should be using tos instead of stack.Length:

public void display()
{
    Console.WriteLine("\nthe stack now contains");
    for (int i = 0; i < tos; i++)
        Console.Write(" "+stack[i]);
}

This way only the valid contents of the stack are printed. The lesson in this is to fix the real problem, not try to cover it up.

Narue 5,707 Bad Cop Team Colleague

So should i assign 0 value to the remaining elements when i perform an pop operation.

Unnecessary. The tos field is what determines where the top of the stack is, and when you push to a spot that's previously been populated, just overwrite the value.

However, if you really did need an "empty" integer (which you don't in this case), you could store it as a nullable type.

Narue 5,707 Bad Cop Team Colleague

Borland Builder has been primarily C++ (with C support) for many years. Another option is Microsoft's Visual C++ if you want a visual designer that's integrated into the IDE.

Narue 5,707 Bad Cop Team Colleague

Insertion sort is also inefficient generally but it still have its own uses :)

I don't think you understand the point that's being made. If you're going to use a quadratic sorting algorithm (bubble sort, insertion sort, selection sort, etc...), bubble sort is the worst choice by a significant margin.

Narue 5,707 Bad Cop Team Colleague

Since bubble sort is efficient

I think you meant to type "inefficient". I also like to add the adverb "woefully" since it drives the point home. ;)

you may want to look into some optimizations of bubble sort; there may serve better purpose

Polish a turd and it's still a turd.

Example : Bidirectional bubble sort http://en.wikipedia.org/wiki/Cocktail_sort

Funny you should bring that up, because it has a suitable quote from Knuth:

But none of these refinements leads to an algorithm better than straight insertion [that is, insertion sort]; and we already know that straight insertion isn't suitable for large N. [...] In short, the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems.

Narue 5,707 Bad Cop Team Colleague

You can switch the console text color at will quite easily. Just change it to the desired color before printing the character, then change it back after printing the character:

#include <iostream>
#include <windows.h>

class TextAttr {
    friend std::ostream& operator<<(std::ostream& out, TextAttr attr)
    {
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), attr.value);
        return out;
    }
public:
    explicit TextAttr(WORD attributes): value(attributes) {}
private:
    WORD value;
};

#define FOREGROUND_WHITE (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)

int main()
{
    std::cout << "Regular text\n"
              << TextAttr(FOREGROUND_INTENSITY | FOREGROUND_GREEN)
              << "Bright green text\n"
              << TextAttr(FOREGROUND_WHITE)
              << "Back to regular\n";
}
Narue 5,707 Bad Cop Team Colleague

It's a pointer to the object, so while the this pointer itself can be described as private, you can still access the address of the object anywhere the object is in scope.

Narue 5,707 Bad Cop Team Colleague

plz help me to know..whether this pointer in c++ is public access or private access

Um...what?

Narue 5,707 Bad Cop Team Colleague

It's probably in reference to floating-point.

Narue 5,707 Bad Cop Team Colleague

Last printf statement should not execute because child has returned to kernel using _exit(0); flushing all open streams and closing any open file descriptor.

IIRC, most versions of vfork() copy file descriptors, so closing them in the child is safe. However, I'm not 100% sure, so once again I'll recommend using fork() instead of vfork(). The potential performance benefits aren't worth the risk.

Narue 5,707 Bad Cop Team Colleague

Both are wrong and invoke undefined behavior. You should be calling _exit(0) because it doesn't perform any cleanup in the child, it just ends the process. Since vfork() shares process memory between parent and child, letting the child perform process cleanup is a Bad Thing™.

Technically, the way you're using vfork() is undefined regardless of your exit strategy, as allowed actions in the child are severely limited:

(From POSIX.1) The vfork() function has the same effect as fork(2), except
that the behavior is undefined if the process created by vfork() either
modifies any data other than a variable of type pid_t used to store the return
value from vfork(), or returns from the function in which vfork() was called,
or calls any other function before successfully calling _exit(2) or one of the
exec(3) family of functions.

In other words, both the printf() call and modifying k in the child are not allowed. I'd suggest you forget that vfork() exists and simply use fork().

Narue 5,707 Bad Cop Team Colleague

Hi, I've tried your way to modify my code, but it's still failing. Why is it so?

Well, since I tested the code before posting it, my guess is that you incorporated the changes into your code incorrectly. Assuming the file opens successfully, it's also possible that it doesn't contain valid integers in the expected order, but I can't confirm that because you didn't provide a sample.

Narue 5,707 Bad Cop Team Colleague

You're printing the value with %d, which is limited to signed int. The C99 specifier for unsigned long long is %llu:

#include <stdio.h>

int main(void)
{
    unsigned long long int cnt;
    
    for (cnt = 0; cnt <= 4026531840; cnt++)
        printf("%llu\n", cnt);
}
hkdani commented: Demonstrates an amazing ability to quickly solve problems not easily solved by others. Shows great depth of knowledge and a solid background based on in depth studies. +5
Narue 5,707 Bad Cop Team Colleague

but I have the const int Max = 7; isnt MAX 7? Thats what the teacher instructed to use:

const int MAX = 7;
float highs[MAX];
float lows[MAX];

You have an array of 7 elements indexed from 0 to 6. The 7th element (ie. highs[7] or lows[7]) does not exist. Aside from the two things I mentioned, your code is acceptable. Those are the two problems that are holding you back.

Narue 5,707 Bad Cop Team Colleague

Two biggest problems:

  1. count and counts are never initialized. You should initialize them both to 0.
  2. In your averaging loop, you always use lows[MAX] . It should be lows[i] . lows[MAX] doesn't exist.
Narue 5,707 Bad Cop Team Colleague
fscanf(inputFile,"%d\n");

This is wrong. Whether you plan on using the value or not, it has to be stored in an object:

fscanf(inputFile, "%d", &ip);

However, you can tell fscanf() to throw it away with a modification to the specifier:

fscanf(inputFile, "%*d");

Finally, don't put '\n' in the fscanf() format string unless you really know what you're doing. *scanf() is not *printf(), despite the similarities. What works well with *printf() will totally mess you up with *scanf(), and literal whitespace is one of those things.

fscanf(inputFile," ");

This is redundant. The %d specifier will strip leading whitespace by default.

return;			/*Empty return*/
fclose(inputFile); /*Close the file stream*/

FYI, when you return from a function, every statement after the return does not execute. So your file isn't being closed.

it appears such a funny number -858993460...

That funny number is indicative of an uninitialized variable. In this case it means fscanf() is failing in some way.

Compare and contrast your code with mine:

void readinput(int in[][MAXCOLS])
{
    FILE *fp = fopen("MatrixA.txt", "r");
    
    if (fp == 0) {
        // Handle file open failure
        return;
    }
    
    // Skip N unused integers
    for (int i = 0; i < 2; i++)
        fscanf(fp, "%*d");

    // Populate the matrix
    for (int row = 0; row < MAXROWS; row++) {
        for (int col = 0; col < MAXCOLS; col++)
            fscanf(fp, "%d", &in[row][col]);
    }

    fclose(fp);
}
Narue 5,707 Bad Cop Team Colleague

now I'm guessing it's because scanf("%d") can't read floating point numbers

Good call. %f doesn't work either because scanf() is expecting a pointer to float and you pass a pointer to a double. Use %lf for reading doubles with scanf().

this is a c++ forum.

this is not a c forum.

C++ supports scanf() and printf() too.

Narue 5,707 Bad Cop Team Colleague

I think this thread has gone far enough. Since we're getting into the realm of remedial hacking advice, I'm going to call an end to it.

Narue 5,707 Bad Cop Team Colleague

lets say its the most significant bit

k i just want to check whether the no s even or odd using msb

Apparently you don't understand the difference between most significant and least significant. :icon_rolleyes: If you're checking for even/odd, you test the least significant bit:

if ((value & 1) == 0) {
    // Even
}
else {
    // Odd
}
Narue 5,707 Bad Cop Team Colleague

i just want to extract the last bit of the given variable.

Which bit do you think is the "last bit"? The term is ambiguous as it could be interpreted as either the most significant bit or the least significant bit.

note:dont extract the bits by dividing it by 2

Let me guess: this is a restriction on the homework you so carefully didn't say this question is based upon? :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

it shows when the user peaked at making new posts and stopped making new posts

How would this metric matter?

you can see when the reputation was awarded and when the user was less abusive

The only time this would be more useful than overall reputation at any given point would be for a member who has an overwhelmingly good or bad history and suddenly changed. In my experience this is an extremely rare pattern.

So there are all sorts of things you can find out with charts that are harder to find out with numbers.

I'm not trying to be dismissive of your suggestion, but there are all sorts of things you can find out with charts that are completely useless. Unless the effort involved in implementing this is so trivial as to be virtually zero-cost, there must be some sort of return on that effort to justify adding the feature and maintaining it.

Narue 5,707 Bad Cop Team Colleague

my problem is highly conceptual problem.

when i write: node *new1=malloc(sizeof(node));

it works properly.

but when i write : node *new1=malloc(sizeof(node*));

it starts giving errors.

// node is the structure having a integer and pointer to itself.

If sizeof(node) > sizeof(node*) then you'll have problems because you're allocating less memory to the pointer than you're sure to end up trying to use.

Narue 5,707 Bad Cop Team Colleague

The only application for bubble sort is in the classroom. It's a simple algorithm, arguably the simplest sorting algorithm, and well suited as an introduction to the concept. However, it's hideously inefficient even compared to other quadratic sorting algorithms.

Narue 5,707 Bad Cop Team Colleague

I'm not entirely sure I see the point of these graphs aside from the initial novelty. Keep in mind that there needs to be some sort of justification for a new feature because there's a cost to both the implementation and maintenance going forward. Since I'm reasonably sure Dani has more important things on her plate than pretty pictures with questionable usefulness, I'd start by asking you how we would all benefit from providing more stats on the top members page?

Narue 5,707 Bad Cop Team Colleague

So is this the thing that C can do that C++ can't?

Um, no? C still allows the auto keyword as a storage class specifier, but as Mike said, it's useless to anyone but a compiler writer. As far as C doing something that C++ can't, I'd say C++'s new interpretation of auto is vastly more awesome. So even though C can use auto as a totally redundant and pointless storage class specifier, C++ can use auto for real improvements to the code. Thus C++ wins by a large margin on the auto front. ;)

Even if it is worthless it is cool that you just found an answer to a question that almost every C programer has asked.

That question is only asked by insecure C programmers who are afraid of C++. Besides, there are many better answers to the question, such as implicit conversion of a pointer to void in both directions:

char *p = malloc(100); /* Valid C, invalid C++ */
char *p = (char*)malloc(100); /* Valid C and C++, but frowned upon in C */

By different things in my second post I ment like DIFFERENT things.

Aside from a few minor differences, C++03 is a superset of C95. However, C++11 and C99 have both evolved in different directions, so you can find more DIFFERENT things. Likewise, the C1x changes (not yet complete) will move the bar even further away.

Would the auto spesephyer thing work if I made the project under …

Narue 5,707 Bad Cop Team Colleague

Actually, looking at your code more closely, you're handling all possible character values. There's no need to attempt converting the character to lower case:

num[userstring[c]]++;

Though you'll definitely need to reconsider how you're printing the frequencies. Instead of just the first 28, go with all 256. The bonus of this is you'll capture all characters and not just the latin alphabet.