Narue 5,707 Bad Cop Team Colleague

Most likely your strings aren't being terminated with '\0'. What does the file look like?

Narue 5,707 Bad Cop Team Colleague

>It's standard, if not for beginners.
Which is the single most annoying problem with how C is taught. Pointers are an integral part of the language, and really very simple conceptually. It's my opinion that they should be introduced as early as possible.

>Three ampersand (star) programmers are generally mocked a bit, however.
Three is uncommon, but fine. Four or more might raise some eyebrows though. I've never used more than five in production code.

Narue 5,707 Bad Cop Team Colleague

>What are the default values of the fundamental types?
That's a fun little can of worms. :)

Narue 5,707 Bad Cop Team Colleague

>it is assumed that the user is entering single digit strings (such as "a 1 2 3 d"(enter))
If all you want is single character input, you don't even need scanf. Just use getchar and test for whitespace manually:

int ch;

while ((ch = getchar()) != '\n' && ch != EOF) {
    if (isspace(ch))
        continue;

    printf("Processing '%c'\n", ch);
}

However, I have yet to see such a program that doesn't grow into more than single character words. In that case, scanf can be used without any problems provided the assumption holds that whitespace or end-of-file terminates each word.

One problem in this case is that scanf doesn't differentiate between newlines and other whitespace. It's all the same to scanf. But because scanf stops reading at whitespace, you can read the next character and see which one it was:

#include <stdio.h>

int main(void)
{
    char word[512];
    char next;

    while (scanf("%511s%c", word, &next) >= 1) {
        printf(">%s<\n", word);

        if (next == '\n')
            break;
    }

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

I'll wait to see what the other people reading this thread have to say before giving you a good solution. :)

Narue 5,707 Bad Cop Team Colleague

Did you include the <string> header? Do you have a using namespace std or using std::string somewhere prior to your usage of the string name?

Narue 5,707 Bad Cop Team Colleague
Narue 5,707 Bad Cop Team Colleague

>I observe that the output it gets done only when cin.get(...) is being executed dunno why.
Because cout is tied to cin. When you make an input request on cin, cout is automatically flushed.

>please tell me a way to empty(forcefully output) a buffer at will.
There are a number of ways, but the two most common are:

cout<<endl; // Print a newline and flush
cout<<flush; // Just flush
Narue 5,707 Bad Cop Team Colleague

>The following code swaps values between 2 variables without using a temp variable.....
Actually, it invokes undefined behavior and could really do anything. If you add sequence points between the operations, then the code is technically correct:

a ^= b;
b ^= a;
a ^= b;

Figure out the bit value for a and b, then work it out yourself using the truth table for XOR:

INPUT 	OUTPUT
A 	B 	A XOR B
0 	0 	0
0 	1 	1
1 	0 	1
1 	1 	0

So let's say a == 1010 and b == 0101:

1010 XOR 0101 = 1111 (a = 1111)
0101 XOR 1111 = 1010 (b = 1010)
1111 XOR 1010 = 0101 (a = 0101)

End result, a == 0101 and b == 1010, which is an inversion of the original state. The XOR swap is an archaic trick to avoid the need for a temporary variable. It's still relevant if you're writing assembly or on a severely memory constrained platform, but for the most part not recommended because

  1. As you've proven, it's not as obvious what's going on.
  2. Tricks like this can actually hinder a compiler's optimizer, resulting in less efficient machine code.
  3. It doesn't always work. For example, if you XOR an object with itself, the result is 0 rather than the expected unchanged value. When a common implementation uses pointers, it's not an unexpected situation and needs a special case (which further complicates and slows …
Narue 5,707 Bad Cop Team Colleague
Narue 5,707 Bad Cop Team Colleague

You're not updating the root node:

node *insert(node *parent, node *child)
{
    if (parent == NULL) {
        parent = child;
        return parent;
    } 
    if (child -> val < parent -> val) {
        parent->left = insert(parent -> left, child);
    } else {
        parent->right = insert(parent -> right, child);
    }

    return parent;
}
root = insert(root, curr);

The code you have fails because printout doesn't take into account that tree might be a null pointer.

Narue 5,707 Bad Cop Team Colleague

>If it was C++ shouldn't the includes be
Not necessarily. The standard C headers are still supported by standard C++, just deprecated. It's unlikely that they'll be removed from the C++ standard as well, because that would destroy code compatibility with C (a guiding principle from day one).

Narue 5,707 Bad Cop Team Colleague

Please don't create a new thread with the same question. Cross posting is just as bad as posting in the wrong place (if not worse). Instead, flag your own thread as bad with the note "this belongs in so and so forum, please move it" for the moderators. Then they can clean up your mess.

Narue 5,707 Bad Cop Team Colleague

If I was creating this simple binary tree I would create my structure like so

struct tree_el 
{
  int *val;
  struct tree_el *right; 
  struct tree_el *left;
};

With an int pointer...That way you can test if the pointer exists with a simple statement like

struct tree_el *root = (struct tree_el *)malloc(sizeof(struct tree_el));

if (root->val)
{

}

Um, perhaps you could elaborate on the logic of this for us slower kids? Because your idea as stated is both illogical and broken.

>@Narue
>i did not get you. It does compile.

Yes, it does compile. That was my point. gerard was wrong in saying that the code is not C++.

Narue 5,707 Bad Cop Team Colleague

>You know this is written in C not C++...
You know that this compiles as C++ too...oh, apparently not. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

It's evaluated as ((3 + (2 * 3)) + 2), not ((3 + 2) * (3 + 2)). If you don't wrap your macro arguments in parentheses, you may not get the evaluation order you wanted.

Narue 5,707 Bad Cop Team Colleague

>DOES PERFORMING DELETE OPERATION ON A DANGLING POINTER LEAD TO INSTABILITIES?
When you delete an indeterminate pointer, demons fly out of your nose and kill a kitten.

Narue 5,707 Bad Cop Team Colleague

A loop invariant is an assertion that doesn't change between the beginning of the loop and each iteration. In your code, one such assertion is that for any a[x] where x < i, target does not exist. This invariant is true prior to executing the loop because x would be less than 0, which is outside of the bounds of the array. The invariant is true during execution of the loop because you 1) use found as a flag to break the loop when a == target, and 2) do not increment i if target is found. Finally, the invariant is true after the loop because of how the loop is terminated. Either i == n and target does not exist in the entire array, or a is equal to target and target does not exist prior to a (otherwise the loop would have terminated sooner).

int i = 0;
bool found = false;
// Invariant (TRUE): -1 is an invalid index
while (i < n && !found)
{
  // Invariant (TRUE): The loop breaks without incrementing i when target is found
  if (a[i] == target)
    found = true;
  else 
    i = i + 1;
}
// Invariant (TRUE): i == n OR a[i] == target

Pre and post-conditions are not necessarily invariants, but they can be.

timb89 commented: Great Help! +3
Narue 5,707 Bad Cop Team Colleague

>The errors are that IdNode has no member named 'end', 'begin' and 'push_front'. Help guys.
The errors are correct. IdNode indeed has no member named end, begin, or push_front. Your list class does though, so you probably wanted idList to be an object of the list class rather than the IdNode class.

Narue 5,707 Bad Cop Team Colleague

Perhaps if you split up the file reading code and the tree insertion code, you'll see the problem. I really do suggest you read the tutorial I linked to, because you clearly don't understand the logic of inserting into a binary search tree. There's a loop involved there too. Presently the only loop you're using is reading items from the file.

Narue 5,707 Bad Cop Team Colleague

You're essentially using a recursive algorithm without the recursion. Might I suggest this tutorial?

timb89 commented: Helpful and added link which aided in correct answer! +3
Narue 5,707 Bad Cop Team Colleague

>which is a dead link by the way
It's not my fault you can't navigate Boost's web site. I have no trouble reaching the documentation page.

Narue 5,707 Bad Cop Team Colleague

I could speculate, but not being privy to the thought process of the designer makes answering your question difficult.

Narue 5,707 Bad Cop Team Colleague

>Why is there not a <heap> just as is there is a <set>, etc?
<priority_queue>, perhaps?

Narue 5,707 Bad Cop Team Colleague

I take it you've already exhausted the tutorials and documentation on the Boost site?

Narue 5,707 Bad Cop Team Colleague

Provided the items are separated by whitespace, you can use the simplest form of stringstream I/O to break it apart:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::stringstream split("v 0.200006 -0.093641 0.584690");
    std::string token;

    while (split>> token)
        std::cout<< token <<'\n';
}
Narue 5,707 Bad Cop Team Colleague

>mktime ( timeinfo );
I suspect you want this:

rawtime = mktime(timeinfo);

Likewise with rawtime2. Otherwise both will be close enough to the same time (the running time of the program) to compare as 0 seconds.

Narue 5,707 Bad Cop Team Colleague

>Please correct me if i'm wrong with my thought process here.
As long as you recognize that your argument boils down to "I like it this way because it makes more sense to me", it's all good. It's not my place to dictate personal styles, provided you're aware of the alternatives and make an educated choice.

>I just don't think it can always correctly interpret my meaning if I chose the path
>of assumptions and ambiguity for the sake of saving a few extra characters of code.

The problem here is that there's no ambiguity. If you find a compiler that incorrectly interprets your meaning without casting malloc, I'll show you a severely broken compiler.

>Not sure what your trying to prove and who your trying to prove it to with this statement.
It's a compliment (you strike me as a skilled programmer). Would you rather I said your statement was the kind of stupid thing beginners believe and left it at that?

Narue 5,707 Bad Cop Team Colleague

>Is that a strong enough reason not to cast your malloc results to your target?
No, but I find not needing to type out a redundant cast and not needing to mention the target data type at all somewhat compelling:

p = malloc(N * sizeof *p);

>I always cast results so the compiler knows my destination size.
That's the kind of statement I expect to see from someone who doesn't understand how pointers to void work. I'm kind of surprised, to be honest. You seem like you know what you're doing.

>It may not always be necessary
The only time it's necessary to cast malloc in standard C is when writing code that needs to be compilable as both C and C++, and that's a rather small niche.

>Sometimes the compiler can be stupid.
Not that stupid. Many bad practices have been propagated far longer than necessary in the name of "helping" the compiler when the compiler doesn't need any help. One of my pet peeves is programmers who think compiler writers are incompetent.

Narue 5,707 Bad Cop Team Colleague

>How can I make the first line of the text as the filename of the text??
The filename is just a string:

ifstream in("filenames");
string line;

if (getline(in, line)) {
    in.close();
    in.clear();
    in.open(line.c_str());

    // ...
}
Narue 5,707 Bad Cop Team Colleague

You can reuse an ifstream object, but take note that opening and closing files does not affect the stream state. If you open a file, read to EOF, close the file, then open another file, the eofbit will still be set. So do something like this:

ifstream in("first file");

// Read first file

in.close();
in.clear();
in.open("second file");

// Read second file

>for (count = 0; !FILE_READER.eof(); count++)
On a side note, the eof member function generally shouldn't be used as a loop condition because it may introduce a fencepost bug. You can use the result of getline instead, and the bug goes away:

count = 0;

while (getline(FILE_READER, tempArray[count], '\n'))
  ++count;

To properly use eof as a loop condition, you still need to perform subsequent tests to explicitly avoid processing the last record twice:

for (count = 0; !FILE_READER.eof(); count++) {
  if (!getline(FILE_READER, tempArray[count], '\n'))
    break;
}
Narue 5,707 Bad Cop Team Colleague

When you don't pass any arguments to ignore, it reads and discards the next character. In your case, that would be the newline character ('\n'). There's a sticky that explains the issues involved (translation: I don't want to write it all again).

Narue 5,707 Bad Cop Team Colleague

As far as it likely matters to you, they're equally fast.

Narue 5,707 Bad Cop Team Colleague

In getid, what happens when r is NULL?

Narue 5,707 Bad Cop Team Colleague

It's the second one. Your first snippet is two if statements, one with and one without an else clause.

Narue 5,707 Bad Cop Team Colleague

If I understand your question correctly, the compiler is not allowed to reorder struct/class members between access specifiers. You can make the order unspecified like so:

struct Vertex
{
   public: Vector3 p;
   public: Vector3 n;
   public: Vector3 c;
}
Narue 5,707 Bad Cop Team Colleague

>But what are man pages ....
You program on Linux and don't know how to consult the man pages? Open up a command prompt and type "man". :)

>What do you mean by implement...
I mean do it yourself. If the function doesn't exist, write it.

Narue 5,707 Bad Cop Team Colleague

Check your man pages, strrev might actually be present. If not, it's a trivial function to implement for your personal library:

#include <string.h>

#define SWAP(T, a, b) \
    do { T save = (a); (a) = (b); (b) = save; } while (0)

char *reverse_string(char *s)
{
    size_t len = strlen(s);

    if (len > 1) {
        char *a = s;
        char *b = s + len - 1;

        for (; a < b; ++a, --b)
            SWAP(char, *a, *b);
    }

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

>I had no idea you can use a (void*) as a cast.
void* is the generic pointer type. You're pretty much guaranteed to be able to convert a pointer to and from void* without any problems. There's no such guarantee for any other arbitrary combination of pointer types. Performing a safe typecast is your first step in troubleshooting the problem.

>Nor have I seen the wording 'transient pointer'.
It's not official terminology. In fact, I made it up on the spot. ;)

Narue 5,707 Bad Cop Team Colleague

>char str[31], ch;
Let's start with this common error. EOF is guaranteed to be a negative quantity, but char may be unsigned. getc returns int for a reason, and that reason is to guarantee that EOF is representable regardless of the signedness of vanilla char.

>while((ch = getc(fp)) != '\n')
Your loops are contradictory and ultimately infinite. The outer loop waits for EOF, but the inner loop (which is your actual reading loop) doesn't stop when it sees EOF.

creeps commented: THE answer +1
Narue 5,707 Bad Cop Team Colleague

>I was thinking of implementing a hash table function as you mentioned, but the assignment is to make an array.
Hash tables are typically implemented as arrays. In this case, an array of linked lists. So the type of your array should be a pointer to the node type:

node *my_array[N] = {0};
Narue 5,707 Bad Cop Team Colleague

Okay, what do you have so far? It sounds like you're working toward a chained hash table implementation, because the array of linked lists for exact matches is a common collision resolution strategy in hash tables.

Narue 5,707 Bad Cop Team Colleague

>In a contact object I store a pointer, which may be for a BCorp or a BPrsn, so I cast it as a (double*).
I can't begin to fathom why you're using double* instead of void* for a safe transient pointer type. Could you explain your reasoning here?

Narue 5,707 Bad Cop Team Colleague

To create an array of objects without initialization, the object type must have a default constructor. The rule in C++ is that a default constructor is generated for you if you don't explicitly define any constructor explicitly. Your class has a three parameter constructor, so no default constructor is generated automatically. You need to do it explicitly.

Narue 5,707 Bad Cop Team Colleague

Have you specified -lbgi -lgdi32 -luser32 as extra libraries?

Narue 5,707 Bad Cop Team Colleague

Once link becomes a null pointer, you've left the realm of the tree. Assigning to link at that point does nothing productive. What you need to do is save a pointer to the last node before link become null, and then assign tmp to either the lc or rc link (depending on the direction you're moving) of that node:

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

struct node {
    int data;
    struct node *lc;
    struct node *rc;
};

int main()
{
    struct node *start = NULL;
    int i,n,flag;

    printf("how many integers you wish to enter\n");
    scanf("%d",&n);

    for(i=0;i<n;i++) {
        struct node *tmp = malloc(sizeof(struct node));
        int a;

        scanf("%d",&a);

        tmp->data=a;
        tmp->lc=NULL;
        tmp->rc=NULL;
        flag=0;

        if (start==NULL)
            start=tmp;
        else {
            struct node *last = start;
            struct node *link = start;

            while (link!=NULL) {
                last = link;
                if (link->data==a) {
                    printf ("The element already exists");
                    flag=1;
                    break;
                }
                else if (a>link->data) {
                    link=link->rc;
                    printf("rc\n");
                }
                else if (a<link->data) {
                    link=link->lc;
                    printf("lc\n");
                }
            }

            if (flag==0) {
                if (a > last->data)
                    last->rc = tmp;
                else
                    last->lc = tmp;
            }
        }
    }

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

This tutorial might be helpful.

Narue 5,707 Bad Cop Team Colleague

>Is there any documentation on this sort of thing?
There's documentation on stdio, for sure. But the actual implementation is up to the implementor. If you want to know how people usually do it, their code is the best way to go about it.

Narue 5,707 Bad Cop Team Colleague

What will you do when stdout is redirected to a file? The file descriptor approach is conventional, and your flag idea seems awkward at best. There will be a lot of special cases with the flag while a file descriptor just works naturally.

Narue 5,707 Bad Cop Team Colleague

>Actually, it is
Prove it. I can prove otherwise by showing the lack of a definition for flushall in the C standard, so you're already in a hole.

>and but I have experienced myself, somewhat inconsistent behaviour of C++ compilers where they
>give inaccurate result on first compilation mostly one rebuilding in file operations in C.

While at a glance this (and all of your other posts) look like English, they're largely incomprehensible.

Salem commented: Indeed +17