Narue 5,707 Bad Cop Team Colleague

Okay, instead of just guessing and writing random stuff, go read a C++ reference on handling exceptions. Or search google. Of course, there's still the issue of trying to allocate exorbitant amounts of memory.

Salem commented: It was an easy walk to get past AD, now for the long climb to the #1 spot +17
Narue 5,707 Bad Cop Team Colleague

The new operator throws an exception of std::bad_alloc if the allocation fails.

[rhetorical question]
Did you catch the exception?
[/rhetorical question]

Narue 5,707 Bad Cop Team Colleague

But she doesn't say that this must be done using the keyboard.

The implication was for interactive user input, since we were talking about a loop to "flush" standard input, and that's typically only meaningful when it comes to user input from the keyboard. However, the challenge was more of a dismissal of the nonexistent problem rather than an actual challenge that needs to be answered.

Narue 5,707 Bad Cop Team Colleague

A char that has an integer equivalent of 0 is an undefined character on output isn't it?

That's outside the realm of what the C++ standard can dictate. Take it up with your terminal shell. ;)

However, when I use it to mark the end of a string (0 == '\0'), nothing is printed.

Because in that case the character acts as a sentinel.

Narue 5,707 Bad Cop Team Colleague

The closest so far is gcc, at least version 4.6. Visual C++ 2010 has a few features, but not the most useful ones for the everyday programmer. If you're working on Windows, I'd suggest the nuwen build of MinGW (it offers gcc 4.6.1). The problem with nuwen is that presently it doesn't have gdb. But you can get it by downloading the gdb part of TDM-GCC).

Hook that up to your favorite IDE, and you're golden.

Narue 5,707 Bad Cop Team Colleague

It turned out be a space.

You mean your shell interpreted it as a space. The null character is not a space, it's NUL.

won't the clearing process be stopped when the space(corresponding to 0) in between is reached?

The value of ' ' is not 0. In fact, I challenge you to input a character with the value of 0 using cin. It's not as simple as you might think.

Narue 5,707 Bad Cop Team Colleague

Does that change the scope of that function to where it can only be used in the function it is declared in?

Global function definitions must still be at namespace scope, which means that the top-down rule still applies. Anything that comes after the function definition can call it, because the definition also acts as a declaration. However, prior to the definition, the scope of the declaration does indeed limit where the function is visible:

#include <iostream>

int main()
{
    {
        int bar();

        // OK: bar is visible in this scope
        std::cout << bar() << '\n';
    }

    // Not OK: no declaration for bar in scope
    std::cout << bar() << '\n';
}

int foo() // This is also a declaration
{
    return 11;
}

int bar()
{
    // OK: foo is visible in this scope
    return foo();
}
Narue 5,707 Bad Cop Team Colleague

Yep, my guess was correct. Change your code to use this instead:

if (LOWORD(wParam) == 6) {
    char temp[2] = {0};

    temp[0] = A_function();

    SetWindowText(hwnd, temp);
}
Narue 5,707 Bad Cop Team Colleague

The ignore command will get rid of any stray characters that are in there and it won't do anything if there are no stray characters, which is what you want.

That's not quite correct. The ignore function will still block for input if the stream is empty. With one edge case exception, these two snippets are equivalent:

cin.ignore(80, '\n');
{
    char ch;

    while (cin.get(ch) && ch != '\n')
        ;
}

The edge case exception is that ignore() is limited by a count, which could potentially fail to read everything from the stream even if you use the upper limit of std::streamsize (the type used by that count) due to there being more characters in the source than the stream buffer can hold. The loop has no such limitation and will read from the stream until a newline is detected or some kind of failure occurs.

You can get pretty close to a true non-blocking flush using the lessons from my stream flushing thread. Here's some draft code from the I/O chapter of a book I'm working on:

#include <istream>

namespace iosx {
    /// @brief Determines if the next extraction will block.
    ///
    /// @param in The input stream being tested.
    /// @return True if the next extraction will block, false otherwise.
    ///
    /// @remarks The stream is assumed to be interactive and line buffered.
    ///
    template <typename CharT, typename Traits>
    bool is_blocking(std::basic_istream<CharT, Traits>& in)
    {
        typename Traits::int_type nl = Traits::to_int_type(in.widen('\n'));
        typename Traits::int_type last = in.rdbuf()->sungetc();

        if …
Narue 5,707 Bad Cop Team Colleague

In your callback function inside the switch statement you have char A_Function(); . What is this for?

It's a declaration for A_Function(). Placing declarations at deeper than file scope is an older style, and sometimes nonsensical, but there's not really anything wrong with it.

it sometimes outputs values < 1 and > 90

Please post a complete program that we can test. At present, I would guess that you're treating the result of A_Function as a C-style string when it's really just a single char. The result would be that any use of the value as a string would very likely produce extraneous garbage output due to the string not being properly terminated. However, it's hard to say exactly since you've judiciously snipped (the code won't compile) and included your own troubleshooting code (the problematic parts appear to have been commented out).

Narue 5,707 Bad Cop Team Colleague

i want to return a string array so i can use it in my main function. how do i do this?

You don't. Arrays aren't assignable, which means you'd be returning a pointer to either the array itself or a pointer to the first element. Since a local array is destroyed when the function returns, that gives you a dangling pointer. Very bad.

How about using a std::vector or std::array (tr1::array) object instead?

#include <array>
#include <iostream>
#include <string>

using namespace std;

array<string, 5> test()
{
    array<string, 5> a = {"Hello","World","How","Are","You"};

    return a;
}

int main()
{
    array<string, 5> b;

    b = test();

    for (int i = 0; i < b.size(); i++)
        cout << b[i] << endl;
}
Narue 5,707 Bad Cop Team Colleague

Why do you need separate arrays? Just use the index array and a simple expression for figuring out the index.

Narue 5,707 Bad Cop Team Colleague

I have a better idea. You tell us what problem you're trying to solve, and we'll help you come up with a better algorithm.

Salem commented: + +17
Narue 5,707 Bad Cop Team Colleague

So you can read it as 'constant string-reference' instead of 'string const-reference'.

Which goes against the more consistent policy of reading right to left. Both are valid, and since the OP's code used const on the right, I maintained that style.

Narue 5,707 Bad Cop Team Colleague

Put it in your gcc invocation:

all: run
 
 
test: test.c
	gcc -D HELLO test.c -o test
 
run: test
	./test
 
clean:
	rm *~ *.o test
VernonDozier commented: :) +15
Narue 5,707 Bad Cop Team Colleague

Anybody know how to remove the duplicate characters in turbo c++.

There are a number of ways. The brute force method is the probably simplest, where you copy each character that isn't in the other string to a result string:

function set_difference(str1, str2)
    result = ""

    for each c1 in str1
        matched = false

        for each c2 in str2
            if c1 = c2
                matched = true
                break

        if not matched
            result.append c1

    return result

a = "abc"
b = "bcd"
print set_difference(a, b) + set_difference(b, a)

Of course, brute force can be problematic in terms of growth. The longer the strings, the slower the algorithm. Ideally you'd have an algorithm that makes one pass over each string.

The operation you're looking for is called a symmetric difference in set theory. It results in items that are in either set, but not both. A list based XOR, if you will. Assuming both sets are sorted, the single pass algorithm is actually quite simple:

function symmetric_difference(str1, str2)
    result = ""

    for i = 0, j = 0 to str1.len, str2.len
        if str1[i] < str2[j]
            result.append str1[i]
            i = i + 1
        else if str2[j] < str1[i]
            result.append str2[j]
            j = j + 1
        else
            i = i + 1
            j = j + 1

    while i < str1.len
        result.append str1[i]
        i = i + 1

    while j < str2.len
        result.append str2[j]
        j = j + 1

    return result

print symmetric_difference("abc", "bcd")

If you're familiar with merging, you'll see that …

Narue 5,707 Bad Cop Team Colleague

I should also clarify, symbol_data is a vector<string>

Then the code should look like this:

string const& symbol::at(int index) const {
  assert(index < symbol_data.size());
  return symbol_data.at(index);
}
Narue 5,707 Bad Cop Team Colleague

I think this has something to do with the fact that I'm returning a const reference to an object that this function is treating as const.

I think you're smoking crack if you made that connection with the given error. The problem is your syntax in calling size() and at(). Tell me, what is symbol_data.vector ?

Narue 5,707 Bad Cop Team Colleague

Basically give the members the ability to make their own queries

Or you could just, you know, remember the folks who rub you the wrong way. :icon_rolleyes: Ignoring the safety and performance concerns of supporting custom queries, consider that Daniweb's single biggest PEBKAC issue is a rampant failure to click on the [code] buton in the post editor.

Narue 5,707 Bad Cop Team Colleague

That makes no difference. If the arrays are fixed, the strings should be fixed as well to conform to your arbitrary idea of how bytes should be distributed. The same solution of zero padding will work.

Narue 5,707 Bad Cop Team Colleague

Have you tried prepending a '0' to the string before converting it?

Narue 5,707 Bad Cop Team Colleague

>#include <cassert>//what is the use of this???
In that program it's not used. But <cassert> defines the assert macro, which is used for sanity checks:

void foo(int *p)
{
    // Precondition: p is not a null pointer
    assert(p != 0);

    ....
}

Your questions boil down to "How do I convert standard C++ to something that will compile under a pre-standard compiler?". The answer is you don't, it's not worth the effort. Get a newer compiler.

Salem commented: +1 +17
Narue 5,707 Bad Cop Team Colleague

Presumably you're using a vector of std::string. The fstream constructors don't have an overload for std::string, so you need to call c_str():

ifstream file(files[0].c_str());
Narue 5,707 Bad Cop Team Colleague

I suspect what you want are property attributes that affect how the property is displayed in a property grid control. If your class is more than just a design-time component, you can also make use of the PropertyGrid control directly in your own applications.

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

runtime system always have to push the current exception list on the heap to keep track what it can handle

That's one possibility, but it's not required.

so can we conclude handling exception make the program slower as it always have to do a check on a heap?

You can conclude that the use of exceptions does involve some overhead, but your reason is a little simplistic. There are a number of factors involved in the performance of exceptions.

Narue 5,707 Bad Cop Team Colleague

What is the scope of the exception variables when I catch them by reference.

I think you mean what is the lifetime of exception objects. Because the scope is a trivial question: the scope of an exception variable, whether caught by value, pointer, or reference, is the catch block.

The lifetime of an exception object is more interesting, but the simplest "mostly correct" answer is that the object lives as long as there's a handler for the exception.

Narue 5,707 Bad Cop Team Colleague

The complexity they introduced in their attempt to "simplify" the logic was absurd.

Sounds like a straw man to me. Just because they failed miserably at simplifying the logic doesn't mean simplifying the logic is a bad idea. I too have seen such attempts fail, and it's nearly always due to code cowboys who spent more time hacking than designing.

emphasizing this point to a beginner does not always translate correctly in practice

It's quite a bit harder to design clear code with acceptable performance than unclear code with excellent performance. I'd honestly prefer to see beginners fail at the former than not even try.

Narue 5,707 Bad Cop Team Colleague

Finally with my limitted knowledge of C, does declaring Result as static make sense?

It makes sense, but I'd argue that it's not the best choice. If you look at all of the problematic functions throughout the history of C, the ones that use static local storage are consistently on the list. In my experience, a better solution is to have the caller pass in a buffer of a suitable size:

char *IntToBinary(int in_Integer, char *out_Result, size_t in_MaxLen);

I would think that register hint for t could be used

First I'd challenge you to find a modern compiler that doesn't completely ignore the register hint. ;)

Narue 5,707 Bad Cop Team Colleague

>if(chooseType == "a" || "A"){
C++ parses it like this:

if(chooseType == "a" || "A" != 0){

Adjust accordingly.

Narue 5,707 Bad Cop Team Colleague

In such a case it's best to post the code and ask how to make it shorter. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

and if i should not even use a goto statement..
what might be the alternative..??

Are you reading impaired? I've listed several alternatives, and they STILL depend on how strict your definition of iteration and recursion are. Stop asking the same damn question when you need to be more specific. Answer the following questions:

  • If I recursively spawn new threads or processes to do the work, does that count as recursion?
  • If I call a library that performs a loop to do the work, does that count as a loop?
  • If I call another pre-existing program that does the work in an unspecified manner, does that still count as a loop or recursion?
Salem commented: Give it up, they ain't worth the effort +17
Narue 5,707 Bad Cop Team Colleague

I'll save you the trouble of searching around: qsort.

Narue 5,707 Bad Cop Team Colleague

int *ptr=50;

This is attempting to point ptr to address 50. Typically, you can only point to addresses within your process' address space, otherwise you'll get a segmentation fault. Java references are actually gimped pointers, which should give you an idea of how to use C pointers for basic object access. First you need a valid object, then you assign the address of that object to your pointer. Finally, you dereference the pointer to access the object:

#include <stdio.h>

int main(void)
{
    /*
        These two lines are the rough equivalent of 

        Integer p = new Integer(50);
    */
    int obj = 50;
    int *p = &obj;

    printf("%d\n", *p);

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

so can we conclude that there is no chance to do this task without a loop or a recursion?

We can conclude that only because you've completely failed to be clear about what constitutes a loop or recursion. The usual solution is to simulate a loop with goto:

#include <stdio.h>

int main(void)
{
    int limit;

    printf("Enter a limit: ");
    fflush(stdout);

    if (scanf("%d", &limit) == 1) {
        int i = 1;

again:
        if (i < limit) {
            printf("%d\n", i++);
            goto again;
        }
    }

    return 0;
}

This depends on the loophole that "loop" means one of the explicit loop constructs: while, do..while, and for. While goto can be used for circular jumps (looping), that's not its only capability, which potentially excludes it from the restrictions.

Another solution uses looping/recursion hidden behind a library or by spawning threads/processes to simulate recursion. However, all of these can be labeled as loops and recursion depending on how strict you are, so a very specific definition of the program's restriction is needed before any of them can be called a solution.

Narue 5,707 Bad Cop Team Colleague

Not to promote the use of alcohol, but it is in most places legal at least.

Well I turned 21 a few months ago, so I'm wondering what everyone else drinks when relaxing on their off days?

I like:
Miller Lite
Bud Light
Other non-traditional (non-mass-produced) beers like dos equis, killian's irish red
Miller High Life is dirt cheap, so when I'm on a budget it's great.

So, what are you drinking this weekend?

A good single malt scotch whisky, spiced rum, and margaritas (in order of preference) make up my alcohol choices. Occasionally I'll drink wine or beer.

Narue 5,707 Bad Cop Team Colleague

But when I close the file, all the other values become null (0), and only the values I modified stay as they are.

I suspect you're doing more than you say, but each time you open the file strictly for output, it will be truncated to zero length. Try this instead:

fstream saveFile(saveFilePath, ios::in | ios::out | ios::binary);
yoni0505 commented: Helped me to solve a problem! +1
Narue 5,707 Bad Cop Team Colleague

To answer the question in your title, yes. write's first argument must be a pointer to char where the number of available characters starting at that pointer match the second argument.

everything between these values became null.

Can you elaborate? What do you want to happen (with examples) and what's actually happening (with examples)?

Narue 5,707 Bad Cop Team Colleague

Do you know what could be the issue?

Yes, the issue is you not understanding how substr works. The second argument is a count, not an index.

Narue 5,707 Bad Cop Team Colleague

There has to be a loop or recursion in some form somewhere. Since you clearly aren't able to refine your description of the problem to allow for semantic loopholes, the problem is impossible. It cannot be solved on a conventional computer.

Narue 5,707 Bad Cop Team Colleague

i want the question to be solved without any recursion or looping concept for unknown variable range of numbers..

You don't need to repeat the requirements, you need to clarify them. For example, if I write a program that calls another pre-existing program to do the looping, does that still count as using a loop? If I simulate recursion using signals, threads or by spawning new processes, does that still count as recursion?

Narue 5,707 Bad Cop Team Colleague

So you want to print an unknown, variable range of numbers, without using any form of loop or recursion. Pretty much any solution with those restrictions will rely on a hidden loop or recursion at a deeper level. It becomes a question of semantics: "Is this enough of a loop to fall under the restriction?"

Depending on how the question is answered, the problem could be solved with a trick, or it could be impossible.

Narue 5,707 Bad Cop Team Colleague

I believe I have this right ... don't you think so ?

Nope, I don't think so at all. It's clearly stated in our acceptable use policy that accounts are permanent as Daniweb's way of complying with anti-spam guidelines.

Narue 5,707 Bad Cop Team Colleague

I don't want to participate on any forum or receive any kind of information or emails.

This can be accomplished without deleting your account. In fact, I'll go ahead and turn off all notifications for you. Then you can simply never log back into this account again and the effect will serve your purposes.

Narue 5,707 Bad Cop Team Colleague

just for giggles here is a generic approach-ish

Hmm, overkill maybe? That whole process can be accomplished with a non-member function, and the approach can be made fully generic (for types that support operator>>) with argument type deduction:

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

template <typename T>
bool get_next(T& value, std::istream& in = std::cin)
{
    std::string line;

    try {
        if (std::getline(in, line)) {
            std::istringstream iss(line);

            if (iss>> value >> std::ws && iss.eof())
                return true;
        }
    } catch (...) {
        // Collect all exceptions into a failure result
    }

    return false;
}

int main()
{
    float num;

    while (!get_next(num))
        std::cerr<<"Invalid input, please try again: ";

    std::cout<<"Your number is "<< num <<'\n';
}

The problem, of course, is your assumption that there's one item of input for each line. You'll find that as you adjust the solution to allow multiple items per line, it begins to look more and more like how the standard library does things. ;)

Narue 5,707 Bad Cop Team Colleague

>ctrLet[ctc]++;
ctc is an int, which is fine. But ctrLet is also an int. The int type does not support indexing.

Narue 5,707 Bad Cop Team Colleague

What I thought was,with the above code,there won't be a second prompt for input,because,the '5' I entered is already lying in the stream and y will also be given the same value.But it isn't so.Why?

When you successfully read a value from the stream, that value is removed from the stream.

cin.get() extracts characters from the stream.But if it is empty does it ask for another one from the user?

It waits for further input, yes.

Narue 5,707 Bad Cop Team Colleague

1) Where did the "5" come from? Why specifically "5"?

You don't need to know or care yet. When you gain proficiency and want to look into how compilers work at a lower level, fine. But for now, studying how undefined behavior works in practice will just distract you from the task of learning proper C. Further, it might encourage you to rely on dangerous behavior.

Had it returned "0" then I would at least understand from where the value returned came from.

Where would the value of 0 come from if your code didn't explicitly return it? I fail to see how 5 is baffling and 0 is not when they're both complete garbage.

Why isn't there a warning or failure? Neither cc nor gcc complains, even with the -pedantic option.

Your warnings aren't turned up high enough, because I get a warning on all of my compilers. Try -Wall and -WExtra.

Actually, I was under the impression that K&R was the standard for many years!

K&R is split into two parts: a tutorial and a reference. The reference served as something of a poor man's standard until ANSI and ISO rolled out a sufficiently large tome. Provided you follow the best practices given in the book, your own code will be pretty good.

Though, I can recompile and run and still get "5" so I actually think that there is something intrinsic about the code that gives "5".

I just ran your code in …

Narue 5,707 Bad Cop Team Colleague

I think this is caused by malloc, or something else.

It's caused by something else. That something else is you misusing malloc. Tell me, what is sizeof(btree) and what makes you think it's equal to sizeof(nodo)? Allocating less memory than you use is a good way to corrupt the memory manager.

Narue 5,707 Bad Cop Team Colleague

i want to write a program

the program should be written in C i need it for "borland c"

FYI, nobody here is going to write this for you. We'll help you write it yourself, but that's it.

Narue 5,707 Bad Cop Team Colleague

but why did it return anything at all?

Because you told it to:

int power(int x, int y);

This says "I will return an integer value". Even if you don't explicitly return something, the compiler will generate code to return a value. The compiler also won't stop calls to this function from using the return value. The assumption is that you, the programmer, didn't lie about returning a value. Since you lied, and didn't return a value, you get what you deserve: undefined behavior.

It would be null, 0, or some other logical value.

Okay, how do you plan to represent some logical value without eliminating one valid value from the type? Say you're returning int, every value in the range of int is perfectly valid. So which of those values shall be made not valid such that it can be used as the logical "null" value in the case where a programmer fails to return something? Further, why should the compiler cater to broken code at the expense of valid code?

I need to learn to read between the lines.

Maybe you're the kind of person who's better off just reading the standard rather than tutorials. At least then you'll have the painfully precise language lawyerese.

dotancohen commented: Thank you for your patience explaining. +2