Tom Gunn 1,164 Practically a Master Poster

Can anyone give me some ideas on how to find the middle value between 3 numbers.?

Assuming it is always 3 numbers, and what you want is the median value, here is a simple way. Find the maximum then the minimum and the one you didn't pick is the median. :)

Tom Gunn 1,164 Practically a Master Poster

You do need to do an fseek to that location, but not because C uses separate read and write pointers. The standard says that when switching between read and write mode on a stream, there needs to be a flush or seek between them. So you would read to the location you want to write, then do fseek(strm, 0, SEEK_CUR); to switch the mode without changing the file position.

And keep in mind that you will be overwriting whatever is there, not inserting.

Tom Gunn 1,164 Practically a Master Poster

Typically the two options for a case like this are a count argument and a sentinel argument:

#include <stdio.h>
#include <stdarg.h>

/* gets a count of arguments */
void TestCount(int x, int n, ...)
{
    va_list args;

    va_start(args, n);

    printf("%d: ", x);
    while (--n >= 0) printf("%-3d", va_arg(args, int));
    putchar('\n');

    va_end(args);
}

/* gets a sentinel as the last argument to mark the end */
void TestSentinel(int x, ...)
{
    va_list args;
    int value;

    va_start(args, x);
    printf("%d: ", x);
    while ((value = va_arg(args, int)) != -1) printf("%-3d", value);
    putchar('\n');

    va_end(args);
}

int main()
{
    TestCount(0, 3, 1, 2, 3);
    TestSentinel(1, 1, 2, 3, -1);

    return 0;
}
Tom Gunn 1,164 Practically a Master Poster

..or may be I am missing some option, in witch case, it should be a lot more visible than it is... I couldn't find it ;-)

I can go to the Delphi forum, then under the Related Forum Features box on the right there is a direct link to all Delphi snippets.

Tom Gunn 1,164 Practically a Master Poster

so suppose if we rememeber the previous values of the stack can we expect the same values as out put.

No. That is the nature of undefined behavior, it is unpredictable. We can only speculate about what will happen and hope that it happens consistently.

Tom Gunn 1,164 Practically a Master Poster

can somebody explain the behaviour of the statement

printf("%d");

Undefined. In practice it will probably print whatever is next in the stack and potentially corrupt the rest of your program by moving the stack pointer in an unexpected way.

Tom Gunn 1,164 Practically a Master Poster

Do not write the line in the first place and you do not have to delete it. :)

Tom Gunn 1,164 Practically a Master Poster

its already available for free on internet.

Not legally, AFAIK. Any that you find are pirated and in breach of copyright. You can contact Addison-Wesley and ask them to be sure, but I think you will get the same answer.

Tom Gunn 1,164 Practically a Master Poster

C++ has two kinds of strings. The strings inherited from C are char arrays with a terminating '\0' character. All of the rules for arrays apply, which means you can only return a pointer to the array somehow. But if the array is local to the function returning it, you are returning a bogus pointer. Not a good thing. ;)

The strings defined by C++ are class objects of the std::string type. They have copy semantics, so it is much easier to use them than the C type strings. I recommend that you use C++ strings until you start getting into the lower levels of C++ because C type strings are very easy to get wrong:

#include <iostream>
#include <string>

std::string Name()
{
    return "Tom";
}

int main()
{
    std::string name = Name();

    std::cout << "My name is " << name << '\n';
}
Tom Gunn 1,164 Practically a Master Poster

Isn't it necessary to seed the random number generator if you want good results?

Not at all. The generator is seeded by default to a value of 1. It does not make the sequence returned by rand() any less random. The sequence is deterministic based on the seed, so every time the program runs with a default seed it will produce the same sequence. But the sequence itself is still pseudo random. :)

Tom Gunn 1,164 Practically a Master Poster

Can I enable/disable an #ifdef based on a specific condition?

Yes, but only if the condition is available at compile time. In your case the value of i is a run time quantity, so you cannot use it with the preprocessor. I think what you really want is an if statement:

for (int i=0; i<5; ++i)
{
   printf("Hello #%d", i);

   if (i == 3)
   {
      printf("I wanna be reached only if i == 3, is that possible?");
   }
}
Tom Gunn 1,164 Practically a Master Poster

Why would you consider not seeding the RNG here?

Why would I bother? It is an example program meant to show how the range of rand() can be shifted using modulus. Adding unnecessary code will only muddy the waters.

Tom Gunn 1,164 Practically a Master Poster

Forgot to seed.

You presume that seeding is a required step, which it is not. Design choices are not the same as memory lapses. ;)

Tom Gunn 1,164 Practically a Master Poster

The simplest way to adjust the range of rand() is with the modulus operator:

#include <iostream>
#include <cstdlib>

int main()
{
    for (int x = 0; x < 20; ++x)
    {
        std::cout << (std::rand() % 900 + 100) << '\n';
    }
}

I am sure someone will chime in with the multitude of problems that this solution has, but if you need to worry about those problems, rand() is not the right random number generator for your application. :)

Tom Gunn 1,164 Practically a Master Poster

would the restore code go in the trees constructor or do i need a seperate function to initialize all the nodes?

I would put it in a separate constructor, as well as a public method. The actual implementation could be in a private method that is shared between the two.

should i have the save function called in the case statement or after the loop finishes executing?

Well... That is really up to your application's logic, but there is nothing stopping you from specifying an internal flag that an object should be saved and doing the save in the destructor.

There are as many ways to do this as there are programmers who can write it, so maybe you should try coming up with several proposals and figuring out which of them best meets your needs.

Tom Gunn 1,164 Practically a Master Poster

Some of the tokens are being stored with blank spaces proceeding them.

That sounds like you need to skip leading whitespace at the token level. When resetting start, instead of incrementing it, walk it over all whitespace. The following is a stream of consciousness. It is meant to spark your imagination, not to be an actual plugin for your code:

// start = (finish != string::npos) ? finish + 1 : string::npos;
if ((start = finish) != string::npos)
{
    while (start < str.length() && isspace(str[start])) ++start;
    if (start == str.length()) start = string::npos;
}
Tom Gunn 1,164 Practically a Master Poster

Id like to use fgets, fprintf, and sscanf.

I want it to read/write the first letters then when it detects the first space (" ") and when it detects a "\0", it should just to the next line again the first space and again a "\0" until it reaches EOF

These wants do not jive. If you use fgets() alone, you have no choice but to provide a buffer large enough to hold the maximum expected line length. If you use sscanf() to extract a word, you have no choice but to provide a buffer large enough to hold the maximum expected line length because the whole line could be one big word.

You can skip using sscanf() entirely by searching for the first whitespace in the line and save the memory for the second buffer:

char line[512];

while (fgets(line, sizeof line, filetext))
{
    size_t x = 0;

    while (line[x] && !isspace(line[x])) putc(line[x], filecopied);

    putc('\n', filecopied);
}

The algorithm from the second quote is a viable option, but I would need some convincing to believe that it is a better option than fgets() and sscanf(). Right now I am not sure what it is you want. Dave and I have both given you solutions that match your functional requirement of saving the first word in each line.

Tom Gunn 1,164 Practically a Master Poster

The second menu is legitimate. When you typed something for scanf() to read, you also pressed [Enter], right? That [Enter] is a character too, and it is stored in the stream as '\n'. The first menu is the one you want, but because there is another character ready to be read, scanf() does not block and the loop is run to completion with an invalid option. Then it runs again, and scanf() blocks after the second menu is printed.

Long story short, scanf() does not work well when mixing formatted and unformatted input. %f is formatted input because leading whitespace is discarded and the input string is parsed into a float. %c is unformatted because no parsing is done, no leading whitespace is discarded, and the next character is read regardless of what it is.

Here is a page that describes the problems of reading single characters with scan() and code to work around it.

Tom Gunn 1,164 Practically a Master Poster

i have not yet learned the code to do it and dont want to wait.

You can learn on your own how to do it and not have to wait for your class to catch up. Then again, patience is an important trait for a programmer to have. Rushing through something because you are impatient can have disastrous results later on.

Tom Gunn 1,164 Practically a Master Poster

where is this function and how is it called ?

It is done by the C runtime. The same code that calls main() collects arguments from the command shell and parses them into an array of char pointers.

Tom Gunn 1,164 Practically a Master Poster

Does your AvlNode class have a public default constructor, public destructor, and public assignment operator? Those are the requirements for storage in a container class.

Tom Gunn 1,164 Practically a Master Poster

Try Tom Gunn's code out. Make sure it "works" for all possible test cases (i.e. change line 11 below for every possible test case you can think of and make sure the code "behaves".

It does not, as you proved. I did not consider adjacent punctuation in my haste to get my post out the door and ended up over engineering the whole thing. Since punctuation is always a single character in this case, the simpler solution for matching punctuation works better:

#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> SplitOnPunct(std::string const& str,
                                      std::string const& punct)
{
    std::vector<std::string> vec;

    if (str.length() == 0) return vec;

    std::string::size_type pos, end;

    for (pos = 0; pos != std::string::npos; pos = end)
    {
        end = str.find_first_of(punct, pos);

        if (end == pos && ++end == str.size()) end = std::string::npos;

        vec.push_back(str.substr(pos, end - pos));
    }

    return vec;
}

int main()
{
    std::vector<std::string> vec = SplitOnPunct("dressed(with)", "+-*/<=!>{()};,");

    for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a)
    {
        std::cout << "vector " << a << ": " << vec.at(a) << '\n'; 
    }
}

I still do not guarantee 100% correctness because it is hard to find my own mistakes. ;) All of the basic test cases seem to work though.

AdRock commented: works a treat....exactly what i needed +1
Tom Gunn 1,164 Practically a Master Poster

my question is how its printing o/p on window without refresh() .

In C++ output streams can be tied to input streams so that when a call is made to the input stream, the tied output stream flushes itself. Something like that might be happening here, but that is total speculation. I do not know the answer.

Tom Gunn 1,164 Practically a Master Poster
#include <assert.h>
#include <complex.h>
#include <ctype.h>
#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <inttypes.h>
#include <iso646.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>

It is always good to learn which headers contain which declarations. Including everything under the sun when you use only a small fraction of it is rarely a good idea.

It doesnt write anything to the file so how can I solve it?

Double check the way sscanf() is supposed to be called. What you want are two strings, one for input and one for output:

char line[512];
char word[512];

while (fgets(line, sizeof line, filetext))
{
    if (sscanf(line, "%511s", word) == 1)
    {
        fprintf(filecopied, "%s\n", word);
    }
}
Tom Gunn 1,164 Practically a Master Poster

Should I put delete in the constructor of that class

The destructor, yes. Or better yet, use a smart pointer like auto_ptr where you do not need to worry about deleting it at all.

Tom Gunn 1,164 Practically a Master Poster

There are three steps to inserting in an array:

  1. Find the position of the item being inserted.
  2. Make room for the new item by shifting all items from that position forward one spot to the right.
  3. Copy the new item into the position that was vacated.

Graphically it looks like this:

Step 1, inserting 5:

[0][1][2][3][4][6][7][8][][][]
                ^

Step 2:

[0][1][2][3][4][6][6][7][8][][]
                ^

Step 3:

[0][1][2][3][4][5][6][7][8][][]
                ^

See if you can roll that up into an algorithm.

Tom Gunn 1,164 Practically a Master Poster

So at what point I have to delete this pointer?

As long as you have a copy of the pointer that was returned by new , you can delete it. You said that the pointer is stored in another object, so that object's destructor would probably handle the deletion. Though that is not exactly the best design, IMO.

Tom Gunn 1,164 Practically a Master Poster

for windows getch and getchar can be used using the header file <conio.h>
In linux for the same you require <stdlib.h>

Not quite. getchar() is declared in <stdlib.h>, which is a standard header so every compiler will have it. getch() is typically declared in <conio.h>, but only on some Windows compilers. getch() is not available on Linux except when using the curses library.

ankur_ commented: perfect answers +1
Tom Gunn 1,164 Practically a Master Poster

How would i rewrite that?

Give it a try before asking for help. Depending on your experience solving problems, at least an hour to several hours of solid work at it should be the minimum. Honestly, if somebody tells you how to write the code every time, you will not learn anything substantial and you will end up asking for help with everything.

Tom Gunn 1,164 Practically a Master Poster

There are left over characters in the stream that cin.get() is reading immediately. It is not blocking, so the program ends immediately and I assume the window is closing so you cannot see the output. Try this:

#include <iostream>
using namespace std;

int main()
{
    int length; // this declairs a variable
    int width; // this declairs another variable

    cout <<"Enter The Length: ";
    cin >> length; //input the length

    cout << "Enter The Width: ";
    cin >> width; //input the width

    cout <<"The area is: ";
    cout << length * width; //display the area

    cin.ignore(1024, '\n');
    cin.get();

    return 0;
}

I added the cin.ignore(1024, '\n'); line. 1024 is an arbitrary large value because I did not want to scare you with the more correct numeric_limits<> construction. ;)

Tom Gunn 1,164 Practically a Master Poster

May I impose on you by asking, why clearerr(stdin); is necessary in this particular example?

It is there for C99 compatibility.

What risks I am not seeing when used without it?

In C99 getchar() will continue to return EOF if the error or end of file indicators are set on the stream. The last getchar() will not block, and that defeats the whole purpose of the function. :) In C89 I have not found an implementation that has the same behavior has C99, so it will probably work as intended without the call to clearerr(). But there is also no risk of not calling clearerr() in C89. It is better all around to assume the more strict rules of C99 and expect subsequent calls to an input function to fail after EOF or an error. That way your code works now and is future proofed.

Tom Gunn 1,164 Practically a Master Poster

Your search always starts from position 0, that is why tokens are being duplicated. You need to skip over the extracted tokens as you go. Something like this:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    using namespace std;

    string const punct = "+-*/<=!>{()};,";

    string str = "dressed(with)";
    string::size_type pos = 0;
    vector<string> vec;

    while (pos != string::npos)
    {
        string::size_type end = str.find_first_of(punct, pos);

        if (end == pos) end = str.find_first_not_of(punct, pos);

        vec.push_back(str.substr(pos, end - pos));
        pos = end;
    }

    for (int a = 0; a < vec.size(); ++a)
    {
        cout << "vector " << a << ": " << vec.at(a) << '\n'; 
    }

    return 0;
}
VernonDozier commented: Nice snippet. +9
AdRock commented: thank you for your help +1
Tom Gunn 1,164 Practically a Master Poster

That class has a kind of strange way of implementing a failed search. In the constructor you pass a bogus object that will act as the sentinel value, and find() returns that object if it fails. So in your case you will compare mytree->find(joe) against bob , since you passed bob as the constructor argument.

Tom Gunn 1,164 Practically a Master Poster

Do a Google search. You can download the runtime as an redistributable package from M$.

Tom Gunn 1,164 Practically a Master Poster

To add to dkalita's reply, the array decaying into a pointer rule only applies to the first dimension. The pointer version of your 2D array function parameter is int (*)[MAX_COL] . You can change your function in either of these two ways:

void fnGetMatrix(int aiMat[][MAX_COL,int *iNoOfRows,int *iNoOfCol)
void fnGetMatrix(int (*aiMat)[MAX_COL],int *iNoOfRows,int *iNoOfCol)

The size in the first dimension does not matter, but it is easier to copy the array declaration and match it exactly so that you do not need to worry about mismatches like the one you discovered:

void fnGetMatrix(int aiMat[MAX_ROW][MAX_COL],int *iNoOfRows,int *iNoOfCol)
Tom Gunn 1,164 Practically a Master Poster

when i press Ctrl+F9 , the output screen comes and goes without stopping for a while.

Please note that i have included "#include<stdio.h>" and i am using "getchar()" function do stop the screen.

A previous call to scanf() of getchar() is probably leaving characters in the stream. The getchar() you are using to stop the screen only works if the stream is completely empty. You can fix that by adding a loop that reads and throws away characters until a line break is found. Here is a utility function that can do what you want:

void PauseForUser(int promptUser, int clearStream)
{
    if (clearStream)
    {
        int c;

        while ((c = getchar()) != '\n' && c != EOF)
        {
            /* all work in condition */
        }

        clearerr(stdin);
    }

    if (promptUser) fputs("Press [Enter] to continue", stdout);

    getchar();
}

In your code it might be called as PauseForUser(1, 1); .

may I know the hazards or any side-effect of using getch() it in TurboC.

Turbo C is becoming increasingly less compatible with the rest of the world as it ages, and using getch() is one way to lock your code into a specific compiler. The graphics.h header is another, worse way.

Using getchar() we have to press the enter key but using getch() we can just press any key then why getchar() instead of getch().

IMO that is not a deal breaker for getchar(), and it is not enough of a benefit to add an extra portability concern. Personally, I think …

Tom Gunn 1,164 Practically a Master Poster

Is there any other hints or ideas on why it is not working? because I am stuck and don't know what to do.

Your printStack() method is wrong because it prints the stack and clears it at the same time. That is problem #1. If you fix that, then your stack objects will not be cleared when they should be for an accurate 3 part test. That is problem #2.

The printStack() method should look more like this if you intend to have it print and not clear. This fixes problem #1:

template<class Type>
void stackType<Type>::printStack()
{
    for (int x = stackTop-1; x >= 0; --x)
    {
        cout << list[x] << '\n';
    }
}

You can manually clear the stack objects, but a more self contained test would be better. For example, you can generalize the test into a function and then call it 3 times. This allows the stack objects to be destroyed and recreated with each function call, which fixes problem #2:

#include <iostream>

void RunTest(int* values1, int sz1,
             int* values2, int sz2)
{
    using std::cout;

    stackType<int> s1;
    stackType<int> s2;

    for (int x = 0; x < sz1; ++x) s1.push(values1[x]);
    for (int x = 0; x < sz2; ++x) s2.push(values2[x]);

    cout << "s1:\n"; s1.printStack(); cout << '\n';
    cout << "s2:\n"; s2.printStack(); cout << '\n';

    if (s1 == s2) cout << "The 2 stacks are equal\n";
    if (s1 != s2) cout << "The 2 stacks are NOT equal\n";

    cout << "\n\n";
}

int main() 
{
    int …
Tom Gunn 1,164 Practically a Master Poster

Does this mean that my operator== function works fine and I just need to reorganizae my main.cpp?

Precisely. I cannot say for sure that your isEqual() function is working as designed without a thorough test, but my eyeball test did not expose any glaring bugs. ;)

Tom Gunn 1,164 Practically a Master Poster

Are you doing something like the following? It works OK on my end for simple currency:

#include <iostream>
#include <iomanip>

int main()
{
    double values[] =
    {
        12.501,
        1254.0,
        124.15,
        10321,
        1.1256
    };
    const int sz = sizeof values / sizeof *values;

    std::cout.imbue(std::locale(""));

    for (int x = 0; x < sz; ++x)
    {
        std::cout << std::fixed << std::setprecision(2)
                  << '$' << values[x] << '\n';
    }
}
Tom Gunn 1,164 Practically a Master Poster

I get all stacks being equal because you call printStack() on both operands and printStack() pops the contents away. Both stacks are always empty. When doing these tests, make sure that you are clearing out the stack at the right time.

Tom Gunn 1,164 Practically a Master Poster

do you know any method in which to draw hearts all over the screen in C++?

I sure do:

#include <iostream>

int main()
{
    for (int x = 0; x < 1000; ++x) std::cout << "<3";
}

:D

Tom Gunn 1,164 Practically a Master Poster

I just cant seem to fathom the last part of each line is being completely ignored...

I know the answer to this problem because it is a problem I create myself on a regular basis. :) On the last token, finish will be string::npos . After the last token, start should be string::npos so that you do not lose the last token. That means the loop should test on start , and you need to take care not to wrap beyond npos :

start = 0;
finish = tempToken[ x ].find_first_of( " ", start );
while( start != string::npos )
{
    tokens[ y ].tokenString = tempToken[ x ].substr( start, finish - start );
    tokens[ y ].lineNumber = x + 1;
    start = (finish != string::npos) ? finish + 1 : string::npos;
    finish = tempToken[ x ].find_first_of( " ", start );
    y++;
}
Tom Gunn 1,164 Practically a Master Poster

The getline() method works with char pointers, and the non-method getline() works with string objects.

Tom Gunn 1,164 Practically a Master Poster

I/O is kind of complicated in C. Can you list out your questions so that it is easier to answer them? I will be happy to give you all of the details you want, but right now it feels like I would end up writing a small book.

Tom Gunn 1,164 Practically a Master Poster

does it chooses the multipales randomly ?

IIRC, the architecture's page size is the determining factor for the file and section sizes.

also for pe files in memory version is aligned to 0x100 wouldn't that make program bigger in memory than in file ?

The section alignment can be the same as the file alignment or bigger. If it is bigger, then more padding is used in memory, which can be used for data storage.

Tom Gunn 1,164 Practically a Master Poster

how we can check a linkedlist of char have a palindrom or not

The same way you do it with an array. Walk two iterators from each end toward the middle until they meet. If the iterators match the whole way, the sequence is a palindrome. Of course, if the list is singly linked, you cannot have an iterator from back to front, but that is easy to work around with a little extra effort. Recursion comes to mind as a first attempt, even though it is not the best use of recursion. ;)

Tom Gunn 1,164 Practically a Master Poster

It works OK for me. Maybe the problem is how you are printing the double that atof() returns. What does the following program print when you run it?

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>

int main()
{
    std::string s("500.00");

    std::cout << std::fixed << std::setprecision(2)
              << std::atof(s.c_str()) << '\n';
}
Tom Gunn 1,164 Practically a Master Poster

getch();

This may or may not work. getch() is not a standard function and not all compilers implement it as an extension. If the only goal is to keep the window open, any blocking read will do:

#include <iostream>

int main()
{
    std::cout << "Hello world!\n";

    // blocking read to keep the window open
    std::cout << "Press [Enter] to continue";
    std::cin.get();
}

This program is portable because cin.get() is a standard method with well defined behavior.

Tom Gunn 1,164 Practically a Master Poster

Do not forget to enter curses mode before using getch() and leave curses mode when you are done:

#include <ncurses.h>

int main()
{
    initscr();
    printw("Enter a character: ");
    printw("You entered '%c'\n", getch());
    refresh();
    endwin();

    return 0;
}
Tom Gunn 1,164 Practically a Master Poster

i can't get how can i use that in a program .

alloca() is used just like malloc(). The difference is how they work under the hood.

and what is the advantage of such a function.

  • alloca() is faster because it just needs to adjust the stack pointer. malloc() has a lot of bookkeeping on top of requesting heap memory.
  • alloca() is easier to use because you do not need a corresponding call to free() like with malloc().

Unfortunately, the disadvantages outweigh the advantages such that alloca() is not recommended. Here is what NetBSD's man page says:

BUGS
The alloca() function is machine dependent; its use is discouraged.

The alloca() function is slightly unsafe because it cannot ensure that
the pointer returned points to a valid and usable block of memory. The
allocation made may exceed the bounds of the stack, or even go further
into other objects in memory, and alloca() cannot determine such an
error. Avoid alloca() with large unbounded allocations.