Thread: basic program - strange error

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    5

    basic program - strange error

    Hey everyone,

    I'm fairly new to programming. I've done C and i'm now learning C++. According to my curriculum i'm now considered an intermediate programmer. But I still consider myself an amateur!

    Well here is the prgm i'm having problems with:

    Code:
    #include <iostream>
    #include <stdlib.h>
    #include <iomanip>
    #include <conio.h>
    
    using namespace std;
    
    
    template <typename Type>
    int indsearch (Type *array, int size, Type vsearch)
    {
            for (int x=0; x<=size; x++)
            {
                    if (array[x]==vsearch)
                    return x+1;
            }
            return -1;
    }
    
    template <typename Type>
    int countx (Type *array, int size, Type vsearch)
    {       int occur=0;
            for (int x=0; x<=size; x++)
            {
                    if (array[x]==vsearch)
                    occur++;
            }
            return occur;
    }
    
    template <typename Type>
    Type maxValue (Type *array, int size)
    {
            Type maxv = array[0];
            for (int x=1; x<=size; x++)
            {
                    if (array[x]>maxv)
                    maxv=array[x];
            }
            return maxv;
    }
    
    
    int main()
    {
    
            cout<<setiosflags (ios::fixed);
            cout<<setprecision(2);
            int isize, irange, isearch;    //?size: how many elements in array. ?range: range for random #'s
            int *iptr;                     //?search: Number to be searched for in array
            float fsize, frange, fsearch;
            float *fptr;
    
    
            cout<<"Please enter INTEGER array size: ";
            cin>>isize;
            iptr=new int [isize];
            if (iptr==0)
            {exit(1);}       //not working
    
            cout<<endl<<"Please enter INTEGER array range: ";
            cin>>irange;
    
            cout<<endl<<"Please enter FLOAT array size: ";
            cin>>fsize;
            fptr=new float [fsize];
            if (!fptr)
            {exit(1);}       //not working
    
            cout<<endl<<"Please enter FLOAT array range: ";
            cin>>frange;
    //************************ARRAY SIZE AND RANGE RETRIEVAL END******************
    
            randomize();                       //random number generator for INT
            for (int i=0; i<isize; i++)
            {
            iptr[i] = random(irange)+1;
            cout<<iptr[i]<<endl;
            }
    
            cout<<endl;
    
            for (int j=0; j<fsize; j++)          //random number generator for FLOAT
            {
            fptr[j] = frange*((float)rand()/RAND_MAX);  //(float)rand()/RAND_MAX will provide
            cout<<fptr[j]<<endl;                        //a product between 0-1 as a float.
            }
    
            int choice;
            do{
            cout<<setw(20)<<endl<<"MAIN MENU";
            cout<<endl<<endl<<"Please Choose an Array to check: ";
            cout<<endl<<"1. Integer Array";
            cout<<endl<<"2. Float Array";
            cout<<endl<<"3. Exit";
            cout<<endl<<"-> ";
            cin>>choice;
            //clrscr();
    
    
                    if (choice==1)
                    {
                            do{
                            cout<<endl<<"1. Search for value in array";
                            cout<<endl<<"2. Check number of occurences in array";
                            cout<<endl<<"3. Check maximum value in array";
                            cout<<endl<<"4. Go Back";
                            cout<<endl<<"-> ";
                            cin>>choice;
                            //clrscr();
                            switch(choice)
                            {
                                    case 1:
                                      {      cout<<endl<<"Please enter value to be searched: ";
                                             cin>>isearch;
                                             isearch=indsearch (iptr, isize, isearch);
                                             if (isearch >= 0)
                                             cout<<endl<<"VALUE FOUND--INDEX: "<<isearch<<endl;
                                             else
                                             cout<<endl<<"VALUE NOT FOUND"<<endl;
                                             cout<<endl<<endl<<"Press any key to continue..";
                                             getch();
                                             //clrscr();
                                      }     break;
    
                                    case 2:
                                       {     cout<<endl<<"Please enter value to be searched: ";
                                             cin>>isearch;
                                             int ioccur=countx(iptr, isize, isearch);
                                             cout<<endl<<"Value was found "<<ioccur<<" time(s)";
                                             cout<<endl<<endl<<"Press any key to continue..";
                                             getch();
                                             //clrscr();
                                       }    break;
    
                                    case 3:
                                       {     int imax=maxValue (iptr, isize);
                                             cout<<endl<<"The maximum value is: "<<imax<<endl;
                                       }     break;
                             }
                                    }while(choice!=4);      //leaves 1st switch
                     }
                            if (choice==2)
                    {
                            do{
                            cout<<endl<<"1. Search for value in array";
                            cout<<endl<<"2. Check number of occurences in array";
                            cout<<endl<<"3. Check maximum value in array";
                            cout<<endl<<"4. Go Back";
                            cout<<endl<<"-> ";
                            cin>>choice;
                            //clrscr();
                            switch(choice)
                            {
                                    case 1:
                                       {     cout<<endl<<"Please enter value to be searched: ";
                                             cin>>fsearch;
                                             fsearch=indsearch (fptr, fsize, fsearch);
                                             if (fsearch >= 0)
                                             cout<<endl<<"VALUE FOUND";
                                             else
                                             cout<<endl<<"VALUE NOT FOUND";
                                             cout<<endl<<endl<<"Press any key to continue..";
                                             getch();
                                             //clrscr();
                                        }    break;
    
                                    case 2:
                                       {     cout<<endl<<"Please enter value to be searched: ";
                                             cin>>fsearch;
                                             int foccur=countx(fptr, fsize, fsearch);
                                             cout<<endl<<"Value was found "<<foccur<<" time(s)";
                                             cout<<endl<<endl<<"Press any key to continue..";
                                             getch();
                                             //clrscr();
                                        }    break;
    
                                    case 3:
                                      {      float fmax = maxValue (fptr, fsize);
                                             cout<<endl<<"The maximum value is: "<<fmax<<endl;
                                      }      break;
                            }
    
                               }while (choice!=4); //leaves 2nd switch
                           }
                          }while (choice!=3); //quits main program
    
            getch();
            delete []iptr;
            delete []fptr;
    }
    I'm using C++ Borland Builder Ver. 6 and I can't get the switches to work properly!

    1st Switch:
    -Case 1: OKAY
    -Case 2: OKAY
    -Case 3: ALWAYS RETURNS 40

    2nd Switch:
    -Case 1: 'VALUE NOT FOUND'
    -Case 2: 'Appears 0 time(s)'
    -Case 3: OKAY


    I've been working on this prgm for a few days now and can't fix it!

    Please help a newbie?
    Last edited by simjay; 10-05-2006 at 06:58 PM.

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Put brackets around your cases

    Code:
    switch(val)
    {
            case 1: { /* yr code */ }
            case 2: { /* yr code */ }
            case 3: { /* yr code */ }
    }
    Also, operator new will never return a NULL pointer (it can throw an exception) no need for those checks.

  3. #3
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    in college my c++ teacher always told us to check if new returned NULL (as in there was not enough memory available), never said anything about exception handling for that. is he 100% wrong?

  4. #4
    Registered User
    Join Date
    Sep 2006
    Location
    UK
    Posts
    13
    does it need brackets around a switch statement? i always just use:
    switch(var) {
    default:
    case 1:
    break;
    }

    This always works fine for me. i though the case and break keywords controlled the start and end of each case not any brackets. !?

    Firstly you use the variable 'choice' to start a loop and continue looping until it equals 3, but then inside that loop you change the value of choice and then use it to start a second loop (and third loop). maybe it works but it's not a good idea.

    Code:
    int indsearch (Type *array, int size, Type vsearch)
    {
            for (int x=0; x<=size; x++)
            {
                    if (array[x]==vsearch)
                    return x+1;
            }
            return -1;
    }
    if array position x == vsearch why would you then return x + 1 as the index of the found item ??

  5. #5
    Registered User
    Join Date
    Sep 2006
    Location
    UK
    Posts
    13
    Straight from MSDN :

    "If there is insufficient memory for the allocation request, by default operator new returns NULL. You can change this default behavior by writing a custom exception-handling routine and calling the _set_new_handler run-time library function with your function name as its argument."

    It's always a good idea to check for NULL pointers before trying to use them, a warning message looks alot better than a straight crash.

    If new returns NULL then you probably want to close your app with a warning

  6. #6
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Straight from the C++ FAQ Lite

    [16.6] Do I need to check for NULL after p = new Fred()?

    No! (But if you have an old compiler, you may have to force the new operator to throw an exception if it runs out of memory.)

    It turns out to be a real pain to always write explicit NULL tests after every new allocation. Code like the following is very tedious:

    Fred* p = new Fred();
    if (p == NULL)
    throw std::bad_alloc();

    If your compiler doesn't support (or if you refuse to use) exceptions, your code might be even more tedious:

    Fred* p = new Fred();
    if (p == NULL) {
    std::cerr << "Couldn't allocate memory for a Fred" << std::endl;
    abort();
    }

    Take heart. In C++, if the runtime system cannot allocate sizeof(Fred) bytes of memory during p = new Fred(), a std::bad_alloc exception will be thrown. Unlike malloc(), new never returns NULL!

    Therefore you should simply write:

    Fred* p = new Fred(); // No need to check if p is NULL

    However, if your compiler is old, it may not yet support this. Find out by checking your compiler's documentation under "new". If you have an old compiler, you may have to force the compiler to have this behavior.

    Note: If you are using Microsoft Visual C++, to get new to throw an exception when it fails you must #include some standard header in at least one of your .cpp files. For example, you could #include <new> (or <iostream> or <string> or ...).
    http://www.parashift.com/c++-faq-lit....html#faq-16.6
    http://www.parashift.com/c++-faq-lit....html#faq-16.7
    http://www.parashift.com/c++-faq-lit....html#faq-16.8

  7. #7
    Registered User
    Join Date
    Sep 2006
    Location
    UK
    Posts
    13
    I should have said :

    "If there is insufficient memory for the allocation request, by default operator new returns NULL"

    Is from MSDN for Visual Studio 6

  8. #8
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    VS6 is 8 years old and superseded by 3 (!) successors. Only companies that have to maintain legacy code still hold on to this fossil.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  9. #9
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    There is a nothrow new, that returns a null pointer on falure, but new doesn't.

    no thow new is used like this: "p=new(nothrow) Object();"

    And you don't need brackets inside case statements, but they might make your code easier to follow. They also have the side effect of making any variables declared iside the statement to go out of scope when the closing brace is reached, but that's probably a good thing.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  10. #10
    Registered User
    Join Date
    Oct 2006
    Posts
    5
    Wow thanks for all the replies.

    does it need brackets around a switch statement? i always just use:
    switch(var) {
    default:
    case 1:
    break;
    }

    This always works fine for me. i though the case and break keywords controlled the start and end of each case not any brackets. !?

    Firstly you use the variable 'choice' to start a loop and continue looping until it equals 3, but then inside that loop you change the value of choice and then use it to start a second loop (and third loop). maybe it works but it's not a good idea.


    if array position x == vsearch why would you then return x + 1 as the index of the found item ??
    Well actually I thought the case statements worked that way too. But it reported a strange error, and wouldn't run. When I added the braces, it compiled and executed. As for the choice variable being used, I tried a different one; didn't work.

    Lastly I made it return x+1 so it's more user-friendly. Instead of stating "Index found in element 0", it's easier if it is displayed as "Index 1, Index 2, Index 3..".

    Have you tried running my code in your compiler? That would be interesting.

    THANKS AGAIN!

    P.S Professor told us to check the dynamic array for failure of allocating memory. Or it would result in a crash. Just good programming practice I guess..

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Avoiding Global variables
    By csonx_p in forum Windows Programming
    Replies: 32
    Last Post: 05-19-2008, 12:17 AM
  3. Getting other processes class names
    By Hawkin in forum Windows Programming
    Replies: 3
    Last Post: 03-20-2008, 04:02 PM
  4. failure to import external C libraries in C++ project
    By nocturna_gr in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2007, 03:49 PM
  5. C++ compilation issues
    By Rupan in forum C++ Programming
    Replies: 1
    Last Post: 08-22-2005, 05:45 AM