Narue 5,707 Bad Cop Team Colleague

When starting out, it helps to always use braces for compound statements. Your loop should look like this:

while ( x < y ) {
  x = x + 1;
  cout<< x <<'\n';
}

If you don't have the braces, only the first statement will be the whole of the loop body. So in your code, the loop is translated like this:

while ( x < y ) {
  x = x + 1;
}
Narue 5,707 Bad Cop Team Colleague

>Wow! Didn't mean to tick you off lady
You didn't tick me off. Apparently you're not used to my direct style of help.

>Sorry if I offended you in any way.
The only thing that offends me is that you're wasting my time. You ask for help, offer no useful information when prompted, then run off to try "other stuff" when somebody is clearly willing to help.

So you go try your "other stuff". Just don't be surprised if I'm not interested in helping you when you return.

Narue 5,707 Bad Cop Team Colleague

>Well, as I said in my original post
Then you should name the function read_data_from_a_file_and_store_it_in_three_arrays rather than CompareIDs. I didn't ask you what your code does, I asked you what the code is meant to accomplish at a higher level. Somebody is going to call CompareIDs, why?

>Once the data in the file is stored in three different
>arrays, I can manipulate it any way I want.

At two million lines, the file is reasonably large. You're reaching the point where a braindead approach like allocating memory for all of the data isn't likely to be the best option.

I can tell you exactly how to do what you asked for, and it'll be both shorter and higher quality. But I get the strong impression that what you're asking for isn't really what you want. Any idiot can read strings into arrays. Your code is broken for a reason, and I'm assuming the reason isn't because you're an exceptional idiot.

Narue 5,707 Bad Cop Team Colleague

That function is kind of scary. What exactly is it supposed to accomplish? I'm reasonably sure I can show you a better way to solve the problem.

Narue 5,707 Bad Cop Team Colleague

>Either way, I don't know how I could trick or trap someone... ?
jephthah was probably thinking about the occasional student who tries to get us to do homework by inviting everyone to participate in a "contest".

Narue 5,707 Bad Cop Team Colleague

>gives me a wierd symbol for the area?
area is declared as a char, and cout is assuming you want to print a character rather than the integral value. Change char area; to int area; and you'll get a slightly more reasonable result.

Narue 5,707 Bad Cop Team Colleague

>The code compiles though.
What you're seeing is a silent extension where the compiler treats the size of void as 1. GCC is wrong to allow it in pedantic mode as it's a constraint violation in the standard.

>warning: ISO C90 forbids mixed declarations and code
This should be an error as well.

Narue 5,707 Bad Cop Team Colleague

>You should perhaps try this:
>void* ptr=but_ptr+20;//this is good

Perhaps you should try it first. You have no excuse for giving an answer that will never compile on a conforming C compiler.

ArkM gave the correct answer (and corrected tux's misconception about casting malloc). Alternatively, you can cast the pointer to void to a pointer to an appropriate type, but regardless of how you do it, void* has to be converted to T* to do anything meaningful with it, where T is a non-void type.

Narue 5,707 Bad Cop Team Colleague

>but is there a equation to change the characters hex to decimal because
>sometimes if a string got F or A it will just change that to its ascii value.

There is a compact and easy way to do what you want. You can find details on how to do it here.

p.s. Thanks for ignoring me. I won't waste my time with you anymore. Figure it out yourself.

Narue 5,707 Bad Cop Team Colleague

Treat it as a variation of K&R's atoi. You should already know that you can step through the string and add the characters like so:

result = radix * result + digit;

If radix is 16, you're converting a hexadecimal value. Now all you need to do is figure out how to convert the A-F digits of a hexadecimal number to 10-15 for the digit value in the snippet above. One way is an indexed lookup. First you find the character in a list of digits, then the index tells you its value:

#include <stdio.h>

int main ( void )
{
  const char *digits = "0123456789ABCDEF";
  size_t i;

  for ( i = 0; digits[i] != '\0'; i++ )
    printf ( "%c = %d\n", digits[i], i );  

  return 0;
}

See what you can come up with using those hints.

Narue 5,707 Bad Cop Team Colleague

>I'm sure tux4life was just trying to help.
I didn't imply otherwise. I said "unintentionally misleading you" because he probably hasn't yet learned these nuances, which is quite understandable and there's nothing wrong with that. Now you've both learned something. ;)

>What do you mean about 7-bit being portable
>and 8-bit upper range not portable?

When ASCII was designed, only the first seven bits were required to hold the characters the designers wanted. To save on transmission costs (we're talking about the 1960's here) the 8th bit was left out of the specification and used as an optional parity bit for error checking if desired.

Instead of using the 8th bit as a parity bit, a bunch of people independently decided to extend ASCII to suit their own needs with regional and special characters. The problem now is that while ASCII itself is widely used (to the point of being adopted into Unicode), there are umpteen different versions of extended ASCII.

When I say something isn't portable, I mean that the same code won't work the same way everywhere. In this case, your output when printing the upper range of extended ASCII will vary.

>i'm assuming that to support a 32-bit unicode character using
>a 16-bit byte, it uses 2 bytes for the unicode character.

Bingo. That's precisely how multi-byte character sets work (including Unicode[1]), except with 8-bit bytes being more common. You might find it fun to study how UTF-32, …

VernonDozier commented: Good explanations in this thread. +16
Narue 5,707 Bad Cop Team Colleague

@OP:

I'm sorry to say it, but so far tux has been unintentionally misleading you. Allow me to clarify.

>I've read that the bits in a byte (in c++) are implementation or system dependent.
Yes.

>What does that mean?
It means that you can't rely on a byte always having eight bits.

>Does it mean implementation of c++ or the processor architecture or some other thing?
It's a processor architecture thing.

>And I've read that you should use sizeof to determine the size of a byte?
The size of a byte in C++ is guaranteed to be 1. This can be confusing to some people because the number of bits in a byte can vary, so the actual size of a byte on different systems can be different but the size reported by sizeof will always be 1. You can get the number of bits in a byte by including <climits> and using the CHAR_BIT macro:

#include <climits>
#include <iostream>

int main()
{
    // "byte" and "char" are equivalent terms in C++
    std::cout<<"sizeof char: "<< sizeof ( char ) <<'\n';
    std::cout<<"CHAR_BIT:    "<< CHAR_BIT <<'\n';
}

The output will be 1 and the size of a byte on your system (usually 8).

@tux:

>A byte is just always eight bits
Incorrect. "Byte" is an abstract term for the smallest addressable unit for your system. While more and more systems are gravitating toward the octet (eight bits, for the …

tux4life commented: Excellent! +8
Dave Sinkula commented: Props. +20
Ancient Dragon commented: Excellent :) +36
Narue 5,707 Bad Cop Team Colleague
string assemblyPath = Assembly.GetExecutingAssembly().Location;
string assemblyDir = Path.GetDirectoryName ( assemblyPath );
string soundsPath = Path.Combine ( assemblyDir, "Sounds" );
sknake commented: You did answer the question before me so you deserve the credit +1
Narue 5,707 Bad Cop Team Colleague

>As I can say "Build an operating system." is a single step
It is, but you have to increase the granularity of your steps to come up with reasonable milestones. I find it somewhat humorous that you compare building an operating system to a trivial twenty line homework program.

>My recent interaction with low level languages are responsible for this.
That's a bad thing. Even at the lowest level you still need to keep an abstract view of your design.

Narue 5,707 Bad Cop Team Colleague

>Enlighten me how?
Step 1: Fill the array using rand.
Step 2: Check for zero and if not present, add it to the end.
Step 3: Randomly shuffle the array.

Apparently you have an extremely limited idea of what a step is.

>in two or more statements?
I can do it in one statement, seeing as how a loop is a compound statement and the shuffle can be done with a single loop. See? I can play games with terminology too. ;)

csurfer commented: Nice play ;) +2
Narue 5,707 Bad Cop Team Colleague

>That can complicate things.
Duh. It is an extra step, after all. :icon_rolleyes: On the plus side it adds another level of randomness.

Narue 5,707 Bad Cop Team Colleague

>For the 20th value, if a 0 was not generated, load
>a 0, otherwise get one more random number.

So if 0 was not generated, it'll always be the 20th value? I'd suggest a final step of randomly shuffling the values. That way you get the required 0, but it's not in a predictable location.

Narue 5,707 Bad Cop Team Colleague

Well, do the children need to be in any specific order? If so, you know what to do: keep the vector sorted to maintain that order. That's how you keep track of the nodes.

Narue 5,707 Bad Cop Team Colleague

The same way, except instead of dealing with only two links, you have more than two (usually in an array).

Narue 5,707 Bad Cop Team Colleague

>>Foreach works on the string array, not on the function call.
>yeah that is what i concluded and surprised.

Right. No offense, but that's pretty obvious when you consider that the expression for foreach requires some form of enumerable collection. foreach is really just syntactic sugar that's converted to a more traditional loop using an enumerable interface:

foreach ( string s in deneme() )
{
  listBox1.Items.Add ( s );
}

becomes:

{
  IEnumerator e = deneme().GetEnumerator();

  try {
    string s;

    while ( e.MoveNext() ) {
      s = (string)e.Current;
      listBox1.Items.Add ( s );
    }
  }
  finally {
    // System.String is a sealed type; no disposal
  }
}

You can see from the expansion that deneme is only called once to retrieve the enumerable collection, then the loop traverses the collection. No magic, just clever compiler tricks to make your life easier.

Narue 5,707 Bad Cop Team Colleague

>Also, as a side Q, do you define both of these as C-style strings?
Yes. The defining trait of a C-style string is the null character at the end. String literals guarantee its presence.

Narue 5,707 Bad Cop Team Colleague

The fact that it's printing more than twenty numbers should be a strong indication that your condition for the loop in displayArray is incorrect. Specifically, it's written with a C-style string in mind, not an array of float. Try passing the size to displayArray like you do with setArray. That particular condition style won't work unless you have some kind of sentinel value at the end of the array (which you don't).

Narue 5,707 Bad Cop Team Colleague

>when i tried aux=aux->prox
...aux becomes invalid because aux->prox is an uninitialized pointer. Any further use of aux, except to point it to another address, is doomed to failure.

Narue 5,707 Bad Cop Team Colleague

>Who says using brackets is better?
A lot of people. It's recommended in all coding guidelines I've seen and required in the majority of them. The rationale is that if you add statements to a block without braces and forget to add the braces, you've introduced a difficult to find logic error. I follow the careful coding guideline[1] so it's not an issue which you choose as far as I'm concerned, but you'll find that braces around every compound statement is considered a best practice.

[1] Careful Coding Guideline: Turn your brain on before starting and keep it on while writing code.

iamthwee commented: Yes +21
Narue 5,707 Bad Cop Team Colleague

>>...but #include "stdafx.h" is missing
>Please note that it's not needed for non-Microsoft compilers
It's not needed for Microsoft compilers either. :icon_rolleyes: I hate how they use that as a default include for generated code. That's one of the reasons I always create an empty project with Visual Studio instead of using the templates.

Narue 5,707 Bad Cop Team Colleague

>why does anyone use system("PAUSE"); ??
Because it gives you a pretty message? Because teachers teach it? Because beginners don't, and shouldn't be expected to, know the pitfalls of it?

tux4life commented: Bad teaching practice then :P +7
Narue 5,707 Bad Cop Team Colleague

>i am getting three answers for just one bit on
Can you give me an example? Most likely I'm testing your code based on how it's written, not how you seem to expect it to work. In other words, I can't reproduce your issue.

Narue 5,707 Bad Cop Team Colleague

Simplest solution: store the result values in an array, then traverse the array backward.

Narue 5,707 Bad Cop Team Colleague

Perhaps if you explained exactly what you were expecting and how what you got is different...

Narue 5,707 Bad Cop Team Colleague

I'll admit that my first reply to that thread assumed you had gotten a warning prior to asking the question. Now I'm confused as to why you were irritated enough to ask in the first place. Are you just too sensitive to handle honest people?

Narue 5,707 Bad Cop Team Colleague

>I accidently posted a thread meant for this forum
>and got a tirade of abuse from "you know who".
Please link to the thread you're referring to. Looking at your account, I see you've only started five threads, none of which contain any form of abuse. You've never received a warning or an infraction, and none of your posts appear to have taken abuse either.

All of this "tirade of abuse" and "berating me" came completely out of nowhere. "You know who" isn't helpful either. If you really have a problem with a post, report it as AD suggested. These whines and warnings to others are completely unproductive and unprofessional.

Narue 5,707 Bad Cop Team Colleague

No forum is exempt from moderation. Perhaps you should read and follow the rules instead of whining about it.

Narue 5,707 Bad Cop Team Colleague

1) Functionally, in that situation, the two are the same. What you're seeing in the first example is C's comma operator in action. Occasionally you'll see people use it to avoid braces. Whether that's a good idea is debatable.

2) div_t is a standard structure. Do you have a more specific question about "what's happening"?

Narue 5,707 Bad Cop Team Colleague

The state of the stream and the contents of the buffer are separate. Even though you reset the buffer to a new string, the stream is still in an end-of-file state from the previous read.

You'll notice that out_offset is correctly set to 3 because the stream starts off in a good state when you create it. But the first time you read to the end of the initial buffer, the eofbit is set and changing the contents of the buffer won't make a difference.

Do a buf.clear(); to reset the stream state.

Clockowl commented: To the point and constructive. +2
Narue 5,707 Bad Cop Team Colleague

Subtract '0' from '2' and see what happens. Then do it for '0' through '9' to verify that it works across the board.

Narue 5,707 Bad Cop Team Colleague

>cout << dist[1][1] << endl; // This correctly displays 0 (not initiallized yet)
Which means either you got extremely lucky, your snippet is misleading and dist has static storage duration, or you're relying on a compiler extension that automagically fills arrays with 0. The following would be more correct:

int dist[2000][100] = {0};

>cout << dist[1][1] << endl; // This incorrectly displays 50
It looks correct to me. You just weren't expecting this behavior. For your homework, I want you to figure out the integer value of the character '2'. You can do this by looking at an ASCII table (which matches your result), or by writing a simple test program that casts the character to an integer.

Narue 5,707 Bad Cop Team Colleague

The char type is an integer type, but when you use the << operator to print it, it's assumed that you want to print the character representation. To get the numeric value you can cast to an integer:

#include <iostream>

int main()
{
  const char *s = "test";

  for ( int i = 0; s[i] != '\0'; i++ )
    std::cout<< (int)s[i] <<' ';

  std::cout<<'\n';
}
Narue 5,707 Bad Cop Team Colleague

Did you even bother to read my example? You butchered it beyond comprehension despite the fact that it already does what you're currently asking for. :icon_rolleyes:

[edit]
By the way, I'm merging this into the original thread so you don't confuse the bejeezus out of everyone.
[/edit]

Narue 5,707 Bad Cop Team Colleague

Oddly enough, most of the problems with stream input are solved the same way: read an entire line into a string and then parse that line for validity:

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

int main()
{
    std::string line;

    std::cout<<"> ";

    if ( getline ( std::cin, line ) ) {
        std::istringstream in ( line );
        std::string command;
        int argument;

        if ( in>> command >> argument )
            std::cout<<"Valid\n";
        else
            std::cout<<"Invalid\n";
    }
}
Narue 5,707 Bad Cop Team Colleague

>I have to interview one-and my options are running out.
Why don't you search the forum for similar interviews? Your questions are hardly unique. I know for a fact that I've thoroughly answered each of them for students looking to interview a programmer.

Narue 5,707 Bad Cop Team Colleague

>Is there a way to convert from const char *
>to char * without casting away the const?
Short answer: No.

>I was warned that it could be dangerous and cause crashes
It's const for a reason. For example, when you point to a string literal, the pointer should be declared as "const char *" because string literals are stored in read-only memory. Casting away the const won't change the read-only nature of the data itself, and trying to modify it will probably cause a crash.

You should only cast away const if you're so sure that the chamber is empty, you'd be willing to point the gun at your face and pull the trigger without any hesitation. In all other cases, work around the const. Make a copy, for example:

char *pline = new char[line.size() + 1];

strcpy ( pline, line.c_str() );
htl.add ( pline );
cout<<"added "<< pline <<'\n';

delete[] pline;
Narue 5,707 Bad Cop Team Colleague

>Do you know what happens if atoi fails to convert?
Then a zero value is returned, or am I wrong?

atoi either returns 0 or invokes undefined behavior. But you can't stop the undefined behavior without carefully validating the string before calling atoi. You also can't tell if the 0 is an error or a legitimate conversion without naively validating the string before calling atoi. If you have to validate the string in every case to use a conversion function in a robust way, the function should be avoided.

Narue 5,707 Bad Cop Team Colleague

[psychic debugging]
You probably forgot to terminate your class definition with a semicolon and the constructor definition immediately follows it. The following code should produce a similar error:

class foo {
public:
  foo();
}

foo::foo() {}

The error is saying that the constructor for foo is trying to use the type foo (specified by a class definition) as the return type for the constructor. However, a constructor doesn't have a return type, so the compiler issues a diagnostic.
[/psychic debugging]

Narue 5,707 Bad Cop Team Colleague

You neglected to counter my argument.

Narue 5,707 Bad Cop Team Colleague

>you live in USA-welfare country.
So do you.

>the rest of the world is not as bright as you think
More learning would fix that. :icon_rolleyes:

>you need additional time to learn for fun.
Unless you spend 100% of your time either sleeping or doing a job where you're not allowed to think, I fail to see how additional time is unavailable. Is it so difficult to find 10 minutes in a 24 hour span?

>in Turkey for instance, <snip excuses>
If the interest is there, people will find the time. Even working 12 hours a day, every day of the week, and taking a full 8 hours for sleep, that still only adds up to 140 hours. What are your Turkish people doing for the other 28 hours? How much do you want to bet that it's entertainment?

Narue 5,707 Bad Cop Team Colleague

>do a check to see if the variables exist in my main program
Just how do you plan on doing that? Are you also parsing the code of the main program? If not, do try to remember that variable names are lost during compilation. The big problems is that variable names are not a queryable entity. You need a more abstract form of storage such that you can hold both a conceptual name as well as the paired value for that name. An associative array is ideal, but for shorter lists a simple array will work just as well:

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

#define length(a) (sizeof (a) / sizeof *(a))

struct variable {
    char *name;
    int value;
};

static const char *ini[] = {
    "var1=5",
    "var2=80"
};

int main ( void )
{
    struct variable vars[] = {
        {"var1"},
        {"var2"}
    };
    size_t i;

    for ( i = 0; i < length ( ini ); i++ ) {
        char temp[BUFSIZ];
        char *name;
        size_t j;

        /* Simulate reading from a stream */
        strcpy ( temp, ini[i] );

        if ( ( name = strtok ( temp, "=" ) ) == NULL )
            continue;

        for ( j = 0; j < length ( vars ); j++ ) {
            if ( strcmp ( vars[j].name, name ) == 0 )
                break;
        }

        if ( j != length ( vars ) ) {
            /*
                - Assuming there's another token
                - Assuming the next token is a valid int

                Example only. Don't do this in real code
            */
            vars[j].value = atoi ( strtok ( NULL, "=" ) );
        }
    }

    for ( i = 0; i < length ( vars ); i++ )
        printf ( "%s = %d\n", vars[i].name, vars[i].value );

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

>learning for fun is not for everyone. it is a surplus.
It's a shame, but quite true. There are many people who simply aren't interested in learning more than they have to.

Narue 5,707 Bad Cop Team Colleague

>but do you think you will benefit from learning japanese?
You can benefit from any kind of learning. It doesn't have to be immediately practical.

Narue 5,707 Bad Cop Team Colleague

>Hopefully that cleared up the question
It's about as clear as it was when I first read it, but at least I have a rough idea of what to recommend.

>if 'export' is still the answer, ok
Fortunately, export is not likely to solve anything close to the problem you're having. It looks more like either poor design of the Structure template such that you need to keep specializing it (the standard containers all follow strict rules concerning the abilities of the template parameter type to avoid this).

Would it be possible to show us the definition of the Structure template and a few of the different ways you use it that require specialization?

Narue 5,707 Bad Cop Team Colleague

>I should either live with it or use a compiler that supports "export"?
If the question is whether you should use export or live with keeping template class definitions with the declarations, you should just live with it. export is...problematic. You'd be better off not using it until everybody has more experience with it.

>stinomus: I apologize if you misunderstood what I was asking.
Actually, I was terribly confused by your original question as well. I'm still not 100% sure that export is what you were looking for.