Narue 5,707 Bad Cop Team Colleague

now tell me the logic to build this rather than laughing on me ?

There was more to Walt's post, you should read it rather than shooting back with a question that was already answered.

Narue 5,707 Bad Cop Team Colleague

When the problem description includes "prints really weird lines" then the problem is very likely to be uninitialized strings. I didn't run your code, but I would guess that it stems from writing sporadically to name with the index i . i will increment whether you copy to name or not, which means you'll have holes. Try this instead:

strcpy(name[count],lol[i].name);
Narue 5,707 Bad Cop Team Colleague

Microsoft: "Use the ISO C++ conformant _kbhit"

Conformant as an extension, not as part of the standard library. You're welcome to quote chapter and verse of the standard that defines _kbhit() and prove me wrong, but in the past people have found it difficult to successfully debate the contents of the standard with me. :)

I have been reading the Internet since about 1987.

Congratulations, but longevity does not in itself give you credibility.

[/o.t. rant]

Yes, please. The last thing we need is another self-righteous doorknob playing net nanny where he holds no authority. Though I find it hilarious how the getch() "controversy" is the single most common catalyst for attracting net nannies.

I have always wondered if it would be possible to use __asm to use assembly language to emulate getch().

Certainly. It would be a waste of time in terms of practicality, but an interesting diversion if you've nothing better to do. ;)

Narue 5,707 Bad Cop Team Colleague

well,if we get some questions of this type in exams or so then no one could deduct our marks?haha

If you get questions of that type in exams, you should complain to the instructor because the answer is subjective. Too many tests will post questions like this where the answer depends not on what actually happens, but what the test creator believes will (or should) happen.

But be prepared to prove that the question is erroneous, because almost invariably you'll be marked down for not answering it. Instructors who don't know C well enough to teach it are likely to be stubborn in their ignorance.

Narue 5,707 Bad Cop Team Colleague

does that means we can never calculate the answer?

Not until the undefined behavior is fixed. Amazingly enough, fixing the undefined behavior also gives you control over evaluation of the answer. The reason it's undefined is because the compiler is free to evaluate the expression in multiple ways and all of those ways are equally good.

Narue 5,707 Bad Cop Team Colleague

Exit code 0xC0000005 is an access violation. Your code is broken, but you can search for places where you're accessing an array out of bounds or an uninitialized pointer. Those are the two most common causes of an access violation.

Narue 5,707 Bad Cop Team Colleague
if (ans == "begin")

you can use strcmp from string.h library

ans is an std::string object, the == operator is properly overloaded, so this test is correct. The problem, I suspect, is that the code requests input twice and the OP has incorrect expectations.

Any help would be greatly appreciated, thanks!

No offense, but your code is awful. goto shouldn't be used where a simple loop works, and you don't have any conditions for breaking out of the loop. Notice that in both the "begin" and not "begin" conditions, the behavior is the same: print a message, call _getch(), and restart at the beginning. This can easily be accomplished with a loop:

#include <conio.h>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string ans;
    
    while (true) {
        cout << "Input: ";
        
        // Otherwise the loop is infinite
        if (!getline(cin, ans))
            break;
        
        if (ans == "begin")
            cout << "You typed 'begin'\n";
        else
            cout << "You didn't type 'begin'\n";
            
        _getch();
    }
}

And assuming the "begin" case is for restarting at the beginning and all other cases terminate the loop, you can now add a break or set a flag for the loop's condition in the else clause:

#include <conio.h>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    bool done = false;
    string ans;
    
    while (!done) {
        cout << "Input: ";
        
        // Otherwise the loop is infinite
        if (!getline(cin, ans))
            break;
        
        if (ans == "begin")
            cout << "You typed 'begin'\n";
        else {
            cout << "You …
Narue 5,707 Bad Cop Team Colleague

The idea of a "short" variable name only made sense when memory was very expemsive and the maximum was only 640K RAM.

Um, no. The idea of a "short" variable name still makes sense because names that are too long are still hard to type and still tend to obscure the structure of the code. This crap about memory is silly because the variable name goes away during compilation. Memory usage for variable names only goes as far as the text editor.

It's a matter of common sense and context. i may be a perfectly suitable name for a temporary loop counter, but woefully inadequate for a global. On the other hand, lstr_this_variable_will_only_be_used_under_certain_conditions is way too long and should be shortened. If there's no way to shorten the name, then the variable does too much and should be refactored. maybe could also be fine depending on the context.

Narue 5,707 Bad Cop Team Colleague

But......The thing is, i am the only active one there.....

Yes, IRC hasn't grown much because every new person joins and then leaves in disgust at how inactive it is, thus continuing the vicious cycle. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

so what is this problem ?

Lack of understanding about how the command prompt in Windows works. Yes, you need to type Ctrl+Z on a line by itself for EOF to be properly signaled in your program.

Narue 5,707 Bad Cop Team Colleague

yes i tried google but didnt find anything that was refered to console apps.

Did you not read my first post?

Narue 5,707 Bad Cop Team Colleague

I guess the reputation feature must have been removed

It wasn't removed, it just looks different. On every post you'll find an up and down arrow along with a counter. The counter is the number of people who have clicked the arrows to vote on a post (positive and negative votes correspond to up and down arrows, respectively). When you choose to vote on a post, you have the option of also giving reputation and including a comment, this is where you'll find the reputation feature now.

So rather than removing a feature, Daniweb added one. :) Votes are a way of saying you like or dislike a post without being forced to give out reputation, and reputation can still be given out if you also want to leave feedback in the form of a comment.

Narue 5,707 Bad Cop Team Colleague

Yes but i tried learning opengl and it is pain in the ass to make it work!

If you're going to give up as soon as it gets hard, then programming isn't for you.

What were u saying about double buffering?

Double Buffering.

Narue 5,707 Bad Cop Team Colleague

You've got the right idea, just make sure the details are solid:

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

struct record {
    char name[32];
    double value;
};

int compare(const void *a, const void *b)
{
    const struct record *pa = a;
    const struct record *pb = b;
    
    int diff = strcmp(pa->name, pb->name);
    
    if (diff == 0) {
        if (pa->value < pb->value)
            diff = -1;
        else if (pa->value > pb->value)
            diff = +1;
        else
            diff = 0;
    }
    
    return diff;
}

int main(void)
{
    struct record records[] = {
        {"A", 1},
        {"B", 13},
        {"B", 1},
        {"B", 2},
        {"C", 3},
        {"C", 1}
    };
    int size = 6;
    int i;
    
    qsort(records, size, sizeof(*records), compare);
    
    for (i = 0; i < 6; i++)
        printf("%s %f\n", records[i].name, records[i].value);
    
    return 0;
}
Narue 5,707 Bad Cop Team Colleague

OP clearly has no intention of doing any work, which means this violates our homework rule. Thread closed.

Narue 5,707 Bad Cop Team Colleague

The console isn't meant to support graphics engines. If you want graphics, get a graphics library where you can use tricks like double buffering to avoid the flicker effect. If you want to use ASCII art graphics, be prepared to suffer the limitations of the console. It's that simple.

Narue 5,707 Bad Cop Team Colleague

This code is compile without any errors in my Visual Studio 2010 Ultimate.

C++ is not defined by Visual Studio 2010 Ultimate. For example, on GCC your code fails with two errors:

main.cpp:6:3: error: 'ptr' was not declared in this scope
main.cpp:29:16: error: 'system' was not declared in this scope

Comeau agrees with this assessment:

"ComeauTest.c", line 6: error: identifier "ptr" is undefined
                ptr=this;

Given only that out of three compilers, two of them[1] fail to compile your code, I'd lean toward Visual Studio being wrong. Please provide chapter and verse from the C++ standard that proves GCC and Comeau are broken.

if the compiler is bugged you wouldn't be so stupid

Please provide chapter and verse from the C++ standard before calling other people stupid.


[1] One of those compilers, Comeau, is also widely accepted as the best conforming compiler available as far as standard C++ goes.

Narue 5,707 Bad Cop Team Colleague

Assuming Turbo C's bin directory is in your PATH and the presence of C:\MyCode containing your source files:

C:\MyCode>tcc myprog.c
Narue 5,707 Bad Cop Team Colleague

LET US TAKE A BETTER EXAMPLE
IF YOU HAVE TO ENTER 2 DIFFERENT STRINGS
IF WE ENTER 1ST ONE AND PRES ENTER
IT INPUTS THE FIRST

AND ALSO LETS THAT THE SECOND STRING IS ALREADY ENTERED i.e THE FIRST STRING.......

SO BOTH STRING BECOMES SAME AND NEGLECTS THE SECOND INPUT STAGE.....

AND GIVE RESULT

>>>>TO PREVENT THIS<<<<

WE USE cin.ignored();
or cin.ignored(100,"\n"); // example

That's a better example? :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

I am not sure of this. But see if you can use the following somewhere

scanf("%[^\n]");

This code skips new line

Actually, it expects a single character that isn't a newline. Skipping a newline would look like this:

scanf("%*[\n]");

However, that doesn't accomplish what the OP wanted, which is accepting newlines without echoing them.

Narue 5,707 Bad Cop Team Colleague

If it is because of undefined behavior then how every time answer is coming as 7 6 7.

Undefined is not synonymous with inconsistent. On the same compiler, undefined results could very well be the same for every run. But there's no guarantee of that, or that other compilers or even other versions of the same compiler will have the same result. Undefined means there are no guarantees for the duration of the program (ie. if you invoke undefined behavior, your entire program becomes undefined henceforth).

Narue 5,707 Bad Cop Team Colleague

detectFaces() looks fine, so I suspect that either by misunderstanding or through a typo you've managed to create something that looks like nested functions. For example:

int main(void)
{
    ...

void detectFaces(IplImage *img)
{
    ...

Notice how main() isn't properly terminated with a closing brace. This would result in the compiler recognizing detectFaces as a function definition local to main(), which is illegal in C.

Narue 5,707 Bad Cop Team Colleague

I'm guessing with gcc there will be no optimization, unless called with -O or similar parameters?

It's best not to guess. GCC is very aggressive when it comes to optimization, so a test using assembly output would be the better approach.

Bladtman242 commented: This is great :) +3
Narue 5,707 Bad Cop Team Colleague

I hope I'm posting in the right forum :)

I'm primarily concerned with C compilers and sun's JDK, but general info is more than welcome (Documentation for self-education as well).

Well, if i wrote a program like

int i = 5
printf("i is $d", i);

Would i=5 be stored separately in memory, or would it exactly the same the following?

printf("i is 5");

(perhaps ("i is $d", 5) is more accurate)

If not, one might balance readablity/maintainability against performance (small improvement perhaps, but I'm a sucker for learning these things, if not using them :) )

An optimizing compiler would likely choose your final option, assuming there's nothing in the code that would require i to exist as an actual entity. There are a huge number of factors involved when it comes to optimization though, so without a full example it's hard to tell you what the possible outcomes are.

Narue 5,707 Bad Cop Team Colleague

No user-defined function can run outside main().

Assuming you mean that no user-defined function can run before main (ignoring that you seem to have misunderstood the OP), consider this:

#include <iostream>

class foo {
public:
    foo() { std::cout << "Me first!" << std::endl; }
} obj;

int main()
{
    std::cout << "In main()" << std::endl;
}
LRRR commented: Whenever I read your post, I always learn something new. +2
PrimePackster commented: Can't resist adding reps... +0
Narue 5,707 Bad Cop Team Colleague

I wanna know what type of parser is used in the gcc and turbo c++ compilers. whether a top-down or bottom-up parser is used..... ?

GCC uses a hand written recursive descent parser (ie. it's top-down). I wouldn't be surprised if Turbo C++ worked the same way, though it might use one of the parser generators rather than a hand written approach.

Narue 5,707 Bad Cop Team Colleague

Is it that exit(10); has no role in the code?

That's correct. However, there's a use case where the opposite situation would remove a warning. Some compilers will warn about the following with something akin to "no return from a function with non-void return type":

static int error_code;

...

int main(void)
{
    ...

    exit(error_code);
}

In such a case a common solution is adding a redundant return that will never be executed due to the call to exit():

static int error_code;

...

int main(void)
{
    ...

    exit(error_code);
    return 0;
}

And is the function actually printing anything?

The side effect of calling printf() is that it prints something. :D

Narue 5,707 Bad Cop Team Colleague

But how to improve at seeing all the things that will break?

It's impossible to account for all of the potential problems. Estimates are nothing more than an educated guess. Really all you can do is add padding to the estimate relative to potential unknown factors. As you gain more experience, both the estimates and padding become more accurate.

Narue 5,707 Bad Cop Team Colleague

Let's use a more complete example:

class Foo {
public:
    typedef int SubType;
};

template <class T>
class MyClass {
    typename T::SubType * ptr;
};

int main()
{
    MyClass<Foo> obj;
}

Foo::SubType is clearly a type, right? But in a dependent name context C++ will assume that the dependent name designates an object unless you qualify it with the typename keyword. A dependent name is a name that depends on a template argument (odd that, huh?), and won't be resolved until the template is instantiated. T::SubType is a dependent name because the parent class represented by template parameter T needs to be instantiated before SubType can be successfully resolved. In other words, T::SubType depends on the instantiation of T .

The end result is that MyClass<Foo>::ptr is a pointer to int because T::SubType resolves to Foo::SubType , which is a typedef for int .

Narue 5,707 Bad Cop Team Colleague

But if the function doesn't work, the exit function will end it up and return a code error 10

That's completely wrong. The call to exit() will never occur because there's an unconditional return immediately prior.

what is the relation between int k and return 0?

There's no relation.

why it is returning 0?

Because the convention of C is to return a status code from main. If the status code is 0, that means successful termination. Anything else is unsuccessful.

where it is passing it?

The C runtime environment. Some people will say the operating system, but that's not strictly correct.

who is checking if the function has succeded or not?

Potentially nobody, but it stands to reason that the user or application who initially ran your program should have access to the final status code, right?

Narue 5,707 Bad Cop Team Colleague

what is CSV?

Comma Separated Values. Google it for more details.

Narue 5,707 Bad Cop Team Colleague

Why are you nulling char* parr[maxStrings] = { NULL, NULL, NULL, NULL, NULL }; ?????????

Why not?

i is supposed to be < maxStrings

This is a pointless change as it doesn't make the code better. In fact, C++ convention leans toward using != for such purposes rather than < because it's consistent with the iterator model.

Narue 5,707 Bad Cop Team Colleague

I found out that the element pick random address and two of the address is str_iteration's address and curr_point's address.

str_iteration and curr_point are both separate entities. They each have a unique address that has nothing to do with the addresses of the pointed to objects.

Wait a minute, so it is actually a multi-dimension array?

Not technically, but you can use it as one because it's an array of simulated arrays. Only the first dimension is an actual array, but the second dimension is a pointer with memory allocated by new, which is functionally very similar to an array.

thought so not really understand why not this one?
for (char **p = **curr_point)

Because there's a type mismatch. **curr_point is type char , not char** . You could certainly say char **p = curr_point , but that's no different from your current loop.

I assigning one pointer to another pointer? so, parr is a pointer? hmm now my mind will come out with (array == pointer) =S I missing something here???

I went to great lengths to stress that arrays are not pointers, yet you still gravitated toward that misconception. No, array != pointer, ever. When you say curr_point = parr , it really means curr_point = &parr[0] .

but if I delete either through curr_point(pointer) or the parr(array) itself, that parr that always refer to the first element will refer to garbage value because the value's there being 'deleted' already... well, if …

Narue 5,707 Bad Cop Team Colleague

the error that I got is " 'clrscr' was not declared in this scope "...

Your compiler doesn't support clrscr() in the conio.h library. This is precisely why we discourage it. However, since it's an unnecessary part of the program, you can remove all uses of clrscr().

Narue 5,707 Bad Cop Team Colleague

Vomit yellow? How about doo-doo brown? Or seasick green? I'm a fan of forest green, to be honest, but Dani has invested too much in purple swag to change colors now. ;)

Narue 5,707 Bad Cop Team Colleague
for (char **curr_point = parr, **bound_point = parr + maxStrings;
curr_point < bound_point; ++curr_point)

Please someone correct me, if I am wrong but, I don't think it is safe to use such addition :
**bound_point = parr + maxStrings; maxStrings = 5 it's an int.

The size of a char is 1 byte, but if it was an int (4 byte), this method wouldn't work. In the end of the loop, it would be pointing to the memory area of the second element of the ""array""(int) instead of the desired bound point. (The bound point would be pointing in the second int.)

I believe you're trying to say that addition on a pointer will always use a step size of one byte, which isn't how pointers work. The step size of a pointer depends on the size of the pointed to type, so p + n under the hood is more along the lines of (char*)p + (n * sizeof *p) .

Narue 5,707 Bad Cop Team Colleague

1- element of a vector/array can "share" same address with the vector/array it was put into. (Well, I always thought each value has its own address)
(reference = 2)

The address of the array and the address of the first element are the same. This makes sense when you think of array indexing as an offset from a base address. (base + 0) == base , right? So &base[0] == base as well.

2- from what I learned, when we setup an array, the pointer will referred to the first element automatically, and that's what (I thought) happen on the pointer's pointer's value(**parr and **curr_points)
(reference = 5 / 7)

That's what happens. Though **parr will always produce the same result because you're always accessing parr[0][0] .

3- based on '2-', can anyone give an idea on how to iterate through the pointer's pointer's value? (does ++**curr_point works?) :P

If I understand your question, you still need some form of iterator. You can't use *curr_point directly, but you can use it as a base:

for (char *p = *curr_point; *p != '\0'; p++)
    std::cout << *p << '\n';

The reason you can't use *curr_point directly is somewhat subtle. If it's an actual array then the pointer isn't modifiable and your code will fail. If it's a simulated array as in your example then modifying it will break subsequent code that relies on parr . This is because curr_point is referencing parr , so changes to …

Narue 5,707 Bad Cop Team Colleague

Use whatever you want unless your homework (and this is clearly homework) requires a specific control structure. There's not a single way to accomplish most programming problems, so you need to figure out which ones will work and choose between them.

Narue 5,707 Bad Cop Team Colleague

I would like to know the best beginner book for C++.

The best book is the one you understand that makes the fewest mistakes. I (and most clueful C++ programmers) recommend Accelerated C++ as a first book due to quality, but that doesn't mean it will be a good fit for you.

My teacher has referred Robert Lafore and The Complete Reference.

This suggests that your teacher isn't very good. My condolences. While Robert Lafore doesn't write horrible books, they're still bottom shelf quality-wise. And Herbert Schildt's books have been the butt of jokes for decades.

Narue 5,707 Bad Cop Team Colleague

How do I do that?

Well, you need some sort of dictionary to look up the words, then pick a word that starts with the letter when there are more than one.

Narue 5,707 Bad Cop Team Colleague

if i use atof() function the number is rounded off to 1234567890123460... ???

Can you post a complete test program that shows this round off error? For example, does the following work?

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

int main(void)
{
    const char *s = "1234567890123456";
    
    printf("DBL_MAX: %f\n\n", DBL_MAX);
    printf("Conversion: %f\n", atof(s));
    
    return 0;
}

ram.item_number = (double)atof((char*)im.itemNum);
(Note: both ram.item_number and im.itemNum belong to double datatype.)

If im.itemNum is a double, then your code is flat out wrong and shouldn't compile. If im.itemNum is a string, then the cast is unnecessary. And the cast on atof() is most certainly unnecessary given that atoi() already returns double.

Narue 5,707 Bad Cop Team Colleague

You can open and view source code files with Visual C++, but to build them they must first be part of a project.

Narue 5,707 Bad Cop Team Colleague

The easiest way would probably be split and trim:

string[] parts = LFname.Split(',');

if (parts.Length != 2) {
    // Handle unexpected input
}

textbox1.Text = parts[0].Trim();
textbox2.Text = parts[1].Trim();
Narue 5,707 Bad Cop Team Colleague

It does discusses how the * and & operators do not function identically(?) for chars and ints.

Once again, this is different from pointers in general. It's a specific matter of using pointers to view an object as a different type:

int i = 123;
char *p = (char*)&i; // View i through char colored glasses

This is called type punning, and while pointers make it possible, it doesn't change how pointers work. The * and & operators still do the same thing in the same way. Note that I used a cast to force the result of &i (which is int*) into char*. That's what Stroustrup is talking about with the reinterpret_cast being a better choice. It doesn't change the effect, it just makes your intentions more clear:

int i = 123;
char *p = reinterpret_cast<char*>(&i); // View i through char colored glasses

I will read more on how types affect pointer and de-reference operators.

Read more on pointers vs. references, that's what the difference is. It's a shame that the same operators are reused for completely different purposes, because that's likely to confuse you.

Narue 5,707 Bad Cop Team Colleague

What exactly did you read, and what exactly didn't you understand? Command line parameters are exceedingly simple, which suggests that you didn't try very hard or are over-complicating things.

Narue 5,707 Bad Cop Team Colleague

there is problem , in main

What is problem? :icon_rolleyes: Do you take your car to the mechanic and say "Something is wrong"? Of course not, because the mechanic will find all kinds of things to fix and charge you a buttload of money for being too stupid to give a specific description of what you want fixed. It's something of an idiot tax.

Around here we won't charge you a buttload of money, but we will ignore your pleas for help. Given that you have over 50 posts, you should know how things work and ask a smart question.

Narue 5,707 Bad Cop Team Colleague

You've specified the type of the object, not the type of the literal. An integer literal without any suffix has the type signed int, which means you can't have a value that exceeds the range of signed int[1]. That's why the suffixes are there, so that you can create a literal that fits a larger type than the default.


[1] Compilers will generally warn you to that effect, but still treat the code as if you used a suffix. This is a convenience only, and not required.

Narue 5,707 Bad Cop Team Colleague

As you can see that this code is accessible in turbo C but not in Dev C++

That's because Dev-C++ is properly disallowing a language constraint violation. The address-of operator may only be used on an lvalue. You can use offsetof() to avoid the very hackish calculations that your awful book is encouraging:

#include <stdio.h>
#include <stddef.h>

struct a {
    struct b {
        int i;
        float f;
        char ch;
    } x;
    struct c {
        int j;
        float f;
        char ch;
    } y;
} z;

void fun(struct c *p)
{
    /* Find the offset of the struct c member */
    size_t offset = offsetof(struct a, y);
    
    /* 
        Find the base address of the struct b member 
        since we know it precedes the struct c member
    */
    struct b *address = (struct b*)((char*)p - offset);
    
    /* Hope and pray that what we "know" about struct a is correct */
    address->i = 400;
    address->f = 3.14;
    address->ch = 'c';
}

int main(void)
{
    fun(&z.y);
    printf("\n%d %f %c", z.x.i, z.x.f, z.x.ch);

    return 0;
}

It's still silly and unsafe, but at least the code should build and run on a modern compiler.

Ancient Dragon commented: Learned something new today :) +17
Narue 5,707 Bad Cop Team Colleague

Java is designed for the web.

Actually, it was designed for the early 90s concept of mobile devices and later tweaked to fit the web paradigm when the original target didn't seem marketable anymore.

C on the other hand is for interaction with the hardware.

C is a general purpose programming language that allows low level access to the hardware. Restricting your definition of what a programming language is or isn't will surely blind you to the possibilities that don't fit your definition.

You CANNOT write an operating system in Java.

You should tell the people who have done it so that they can adjust their view of reality accordingly. Also note that an OS written in XYZ doesn't mean only written in XYZ. For example, you'll find that the bootstrapping parts of an OS are typically written in assembly language. But if all other code uses XYZ then it's not incorrect to say the OS is written in XYZ.

Narue 5,707 Bad Cop Team Colleague

Does nesting/recursion work for the dereferencing operator as well?

Certainly:

#include <iostream>

int main()
{
    int i = 123;
    int *p1 = &i;
    int **p2 = &p1;
    int ***p3 = &p2;
    
    std::cout << &p2 << " -- " << p3 << '\n';
    std::cout << &p1 << " -- " << *p3 << '\n';
    std::cout << &i << " -- " << **p3 << '\n';
    std::cout << i << " -- " << ***p3 << '\n';
}
int &i = *p1;
int &&i = **p2;
int &&&i = ***p3;

Applying the & operator to a type is something completely different. It only works as the address-of operator when applied to an object. Specifically, the first line defines a reference to an int, the second line defines an rvalue reference to an lvalue (not legal), and the third line is a syntax error.