Please comment on my integer to string code.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pete Becker

    #16
    Re: Please comment on my integer to string code.

    BobR wrote:
    [color=blue]
    >
    > // > str += charTable[i % base];
    > str += charTable.at( i % base );
    >[/color]

    The data has already been validated. This check adds nothing. The
    original version, with the char array and direct access, had far less
    overhead and was just as robust.

    --

    Pete Becker
    Roundhouse Consulting, Ltd.

    Comment

    • Pete Becker

      #17
      Re: Please comment on my integer to string code.

      Phlip wrote:
      [color=blue]
      >[color=green]
      >>catch(...){
      >>std::cerr<<"c aught ... something"<<std ::endl;
      >>return EXIT_FAILURE;
      >>}[/color]
      >
      >
      > I know a certain lead programmer driven to distraction by code that relied
      > on catch(...). The advice is let the program halt; use a debugger to fix
      > all root causes, and stress-test applications to force out these risks.
      >[/color]

      But it's okay here, since the code will never throw an exception. The
      checking in calls to at() is redundant.

      --

      Pete Becker
      Roundhouse Consulting, Ltd.

      Comment

      • BobR

        #18
        Re: Please comment on my integer to string code.


        Phlip wrote in message ...[color=blue]
        >BobR wrote:[/color]
        [color=blue][color=green]
        >> catch(...){
        >> std::cerr<<"cau ght ... something"<<std ::endl;
        >> return EXIT_FAILURE;
        >> }[/color]
        >
        >I know a certain lead programmer driven to distraction by code that relied
        >on catch(...). The advice is let the program halt; use a debugger to fix
        >all root causes, and stress-test applications to force out these risks.
        >
        >And catch(...) only catches hardware crashes on Win32 as a compiler-specific
        >extension. Other platforms just dump core, meaning they cannot use that
        >trick to maintain their work loops and keep running.
        >
        >--
        > Phlip[/color]

        Good advice.
        But for 'toy' code, it's nice to see *something* output when testing a chunk
        of new code.
        In my experiments with try-catch, I've caught things other than 'hardware'
        (MinGW, win98).

        // ------------------------------------
        class MyError : public std::runtime_er ror { public:
        MyError(std::st ring const &msg = "") : std::runtime_er ror(msg){}
        };
        // ------------------------------------
        void f() throw(MyError){
        throw MyError( "blah-blah" );
        return;
        }
        // ------------------------------------
        // ------------ in main()
        try{ f();}
        // catch(MyError const &x){
        // std::cout<<"MyE rror test: "<<x.what()<<st d::endl;
        // }
        // catch(std::runt ime_error const &error){
        // std::cout<<"std ::runtime_error "<<error.what() <<std::endl;
        // }
        catch(...){
        std::cout<<"som ething TERRIBLE happened,"
        " but, I don't know what!!"<<std::e ndl;
        }
        // ------------
        // - output -
        something TERRIBLE happened, but, I don't know what!!


        Are you saying I can't do that in GNU/Linux, winXP?

        --
        Bob R
        POVrookie


        Comment

        • Phlip

          #19
          Re: Please comment on my integer to string code.

          BobR wrote:
          [color=blue]
          > Are you saying I can't do that in GNU/Linux, winXP?[/color]

          Windows has an extra feature that turns general protection faults (you know;
          crashies. Bad things.) into exceptions that you can catch with catch(int).
          So catch(...) will also catch them.

          Other systems may have similar features. Programmers should develop slowly
          and incrementally enough to discover and write code to catch all "real"
          exceptions, and should treat catch(...) like a failing assert() statement.
          Time to dissect the code looking for a programmer error.

          So, either way, never rely on 'catch(...)' within delivered code.

          --
          Phlip
          http://www.greencheese.org/ZeekLand <-- NOT a blog!!!

          Comment

          • red floyd

            #20
            Re: Please comment on my integer to string code.

            Phlip wrote:[color=blue]
            > BobR wrote:
            >[color=green]
            >> Are you saying I can't do that in GNU/Linux, winXP?[/color]
            >
            > Windows has an extra feature that turns general protection faults (you know;
            > crashies. Bad things.) into exceptions that you can catch with catch(int).
            > So catch(...) will also catch them.[/color]

            We're way OT here, but it turns them into catch(int)? I could never
            figure out C0000005 errors (Win32 equivalent of SegV) turned into.
            That's the main reason I had catch(...) in my code.

            Comment

            • BobR

              #21
              Re: Please comment on my integer to string code. [thank you]


              Phlip,
              Thanks for the info. I appreciate you taking the time.

              I have a lot of fun with try-catch in my 'experiments'. Of course I would
              never do such things in 'real' code. <G> (reserved for critical errors that
              are hard to handle otherwise).

              I'll have to do some more testing next time I'm over on a GNU(Debian)
              partition in this box.

              You ever pop in some screwy stuff like that to rattle your 'lead'? <G>

              --
              Bob R
              POVrookie


              Comment

              • Phlip

                #22
                Re: Please comment on my integer to string code.

                red floyd wrote:
                [color=blue]
                > We're way OT here, but it turns them into catch(int)?[/color]

                The purpose of topicality is to grow a healthy community whose members know
                they can stretch the bounds now and then.
                [color=blue]
                > I could never figure out C0000005 errors (Win32 equivalent of SegV) turned
                > into. That's the main reason I had catch(...) in my code.[/color]

                Google this verbiage:

                "try-except-statement :
                __try compound-statement
                __except ( expression ) compound-statement

                "The try-except statement is a Microsoft extension to the C and C++
                languages that enables 32-bit target applications to gain control when
                events that normally terminate program execution occur. Such events are
                called exceptions, and the mechanism that deals with exceptions is called
                structured exception handling."

                Except it ain't catch, it's __except. That's why it's OT - because nobody
                will crack down on me if I get the natty details wrong.

                --
                Phlip
                http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


                Comment

                • manoj1978@gmail.com

                  #23
                  Re: Please comment on my integer to string code.


                  BobR wrote:[color=blue]
                  > manoj1978@gmail .com wrote in message
                  > <1141916757.291 734.248560@p10g 2000cwp.googleg roups.com>...[/color]
                  [color=blue]
                  > Style-wise, **IMHO**, (at this point) it stinks!! I'd put the 'using *'
                  > inside the function/main if I couldn't type "std::".[/color]
                  thanks.will keep in mind.[color=blue]
                  > My suggestions inline below.
                  >[color=green]
                  > >[/color]
                  > // >char charTable[] = "0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZ";
                  >
                  > std::string charTable( "0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZ" );
                  >[color=green]
                  > >[/color]
                  > // >void printBase(int i, int base){
                  > std::string CalcBase(int i, int base){
                  > using std::abs; // etc.
                  >[color=green]
                  > > if ((abs(base) <= 1) || (abs(base) > 36) || (i == 0)){[/color]
                  > // > cout << "0" << endl;
                  > // > return;
                  > return "0";[color=green]
                  > > }
                  > >
                  > > string str = "";
                  > > if ((base > 0) && (i < 0)){
                  > > str += "-"; // prints "-16 = 10-" for base==16[/color][/color]
                  Thanks.[color=blue][color=green]
                  > > i = -i;[/color][/color]
                  Will this really cause issue if i is smallest negetive int?[color=blue][color=green]
                  > > }
                  > >
                  > > do {
                  > > if (i % base >= 0){[/color]
                  > // > str += charTable[i % base];
                  > str += charTable.at( i % base );
                  >[color=green]
                  > > i = i / base;
                  > > } else {[/color]
                  > // > str += charTable[i % base - base];
                  > str += charTable.at( i % base - base );
                  >[color=green]
                  > > i = i /base + 1;
                  > > }
                  > > } while(i);[/color]
                  > // > reverse(str.beg in(), str.end());
                  > std::reverse(st r.begin(), str.end());
                  >
                  > // prints "-16 = 10-" for base==16[/color]
                  Will this be ok?
                  if (str[0] == '-')
                  std::reverse(st r.begin()+1,str .end());[color=blue]
                  >
                  > // > cout << str << endl;
                  > return str;[color=green]
                  > > } // CalcBase(int,in t)
                  > >
                  > >int main(){[/color]
                  >
                  > try{
                  > for(int i(-55); i <= 55; ++i){
                  > // > cout << i << " = ";
                  > // > printBase( i, -10 );
                  > std::cout << i <<" = "<<CalcBase ( i, -10 )<<std::endl;
                  >[color=green]
                  > > } // for(i)[/color]
                  > } // try
                  > catch(std::out_ of_range &Oor){
                  > std::cerr<<"cau ght "<<Oor.what()<< std::endl;
                  > return EXIT_FAILURE;
                  > }
                  > catch(...){
                  > std::cerr<<"cau ght ... something"<<std ::endl;
                  > return EXIT_FAILURE;
                  > }
                  > return 0;
                  >[color=green]
                  > > } // main()end
                  > >
                  > >Thanks and Regards,
                  > >manoj.[/color]
                  >
                  > // - output - (base==-10)
                  > -55 = 65
                  > -54 = 66
                  > [snip]
                  > -11 = 29
                  > -10 = 10
                  > -9 = 11
                  > -8 = 12
                  > [snip]
                  > -2 = 18
                  > -1 = 19
                  > 0 = 0
                  > 1 = 1
                  > [snip]
                  > 8 = 8
                  > 9 = 9
                  > 10 = 190
                  > 11 = 191
                  > [snip]
                  > 54 = 154
                  > 55 = 155
                  >
                  >
                  > And your C++ problem is?[/color]
                  I modified a C code for this.I havent used C++ much.Want to be sure
                  that,there is no stupid mistakes.[color=blue]
                  >
                  > --
                  > Bob R
                  > POVrookie[/color]
                  Thanks Bob,
                  Regards,
                  manoj.

                  Comment

                  • Victor Bazarov

                    #24
                    Re: Please comment on my integer to string code.

                    manoj1978@gmail .com wrote:[color=blue][color=green]
                    >> manoj1978@gmail .com wrote in message[color=darkred]
                    >>> i = -i;[/color][/color]
                    > Will this really cause issue if i is smallest negetive int?[/color]

                    Whatever you mean by "smallest negetive"...
                    [color=blue]
                    >[..][/color]

                    If 'i' is INT_MIN (and on some systems it's -32768), then change
                    its sign and the result may not be representable in an int. What
                    happens after that is implementation-defined, most likely the 'i'
                    gets truncated, and you get 0. So, -INT_MIN is 0? That doesn't
                    seem right...

                    V
                    --
                    Please remove capital As from my address when replying by mail


                    Comment

                    • manoj1978@gmail.com

                      #25
                      Re: Please comment on my integer to string code.


                      Victor Bazarov wrote:
                      [color=blue]
                      > Whatever you mean by "smallest negetive"...
                      >[color=green]
                      > >[..][/color]
                      >
                      > If 'i' is INT_MIN (and on some systems it's -32768), then change
                      > its sign and the result may not be representable in an int. What
                      > happens after that is implementation-defined, most likely the 'i'
                      > gets truncated, and you get 0. So, -INT_MIN is 0? That doesn't
                      > seem right..[/color]
                      Thanks for the info.
                      Regards,
                      manoj..

                      Comment

                      • Phlip

                        #26
                        Re: Please comment on my integer to string code.

                        manoj1978 wrote:
                        [color=blue][color=green]
                        >> Style-wise, **IMHO**, (at this point) it stinks!! I'd put the 'using *'
                        >> inside the function/main if I couldn't type "std::".[/color][/color]
                        [color=blue]
                        > thanks.will keep in mind.[/color]

                        The ulterior principle here is "give everything the narrowest feasible
                        scope". For example, prefer this:

                        loop thing
                        {
                        int x ...
                        }

                        over this:

                        int x;
                        loop thing
                        {
                        ....
                        }
                        // x not used here

                        If it's not used outside the loop, put it inside the loop block.
                        [color=blue][color=green][color=darkred]
                        >> > i = -i;[/color][/color]
                        > Will this really cause issue if i is smallest negetive int?[/color]

                        Write a test case (one of the assert() lines I pitched that puts in such an
                        input that you reach this line with the smallest int.
                        [color=blue][color=green]
                        >> // > str += charTable[i % base];
                        >> str += charTable.at( i % base );[/color][/color]

                        Note that someone bounced this suggestion. charTable is potentially
                        constant, so it has no need to be a full-fledged string object.

                        Write it like this:

                        char const charTable[] = "0123...Z";
                        [color=blue][color=green]
                        >> // prints "-16 = 10-" for base==16[/color][/color]
                        [color=blue]
                        > Will this be ok?
                        > if (str[0] == '-')
                        > std::reverse(st r.begin()+1,str .end());[/color]

                        I don't know, but I trimmed out the excess stuff from the post, and put
                        blank lines around your question, to make it easier for others to spot and
                        answer.

                        You might also write a test case that forces that situation.

                        --
                        Phlip
                        http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


                        Comment

                        • manoj1978@gmail.com

                          #27
                          Re: Please comment on my integer to string code.


                          Phlip wrote:
                          [color=blue]
                          > manoj1978 wrote:
                          >[color=green][color=darkred]
                          > >> Style-wise, **IMHO**, (at this point) it stinks!! I'd put the 'using *'
                          > >> inside the function/main if I couldn't type "std::".[/color][/color]
                          >[color=green]
                          > > thanks.will keep in mind.[/color]
                          >
                          > The ulterior principle here is "give everything the narrowest feasible
                          > scope". For example, prefer this:
                          >
                          > loop thing
                          > {
                          > int x ...
                          > }
                          >
                          > over this:
                          >
                          > int x;
                          > loop thing
                          > {
                          > ...
                          > }
                          > // x not used here
                          >
                          > If it's not used outside the loop, put it inside the loop block.
                          >[color=green][color=darkred]
                          > >> > i = -i;[/color]
                          > > Will this really cause issue if i is smallest negetive int?[/color]
                          >
                          > Write a test case (one of the assert() lines I pitched that puts in such an
                          > input that you reach this line with the smallest int.[/color]

                          On my system,it remains as it is.I modified the code to treat that
                          input as invalid.
                          [color=blue]
                          >[color=green][color=darkred]
                          > >> // > str += charTable[i % base];
                          > >> str += charTable.at( i % base );[/color][/color]
                          >
                          > Note that someone bounced this suggestion. charTable is potentially
                          > constant, so it has no need to be a full-fledged string object.
                          >
                          > Write it like this:
                          >
                          > char const charTable[] = "0123...Z";[/color]
                          Ok.[color=blue]
                          >[color=green][color=darkred]
                          > >> // prints "-16 = 10-" for base==16[/color][/color]
                          >[color=green]
                          > > Will this be ok?
                          > > if (str[0] == '-')
                          > > std::reverse(st r.begin()+1,str .end());[/color]
                          >
                          > I don't know, but I trimmed out the excess stuff from the post, and put
                          > blank lines around your question, to make it easier for others to spot and
                          > answer.
                          >
                          > You might also write a test case that forces that situation.[/color]
                          I tried with that and it is working fine.want to be sure that it is
                          okay to use that in C++ or does it have any hidden problems.

                          Regards,
                          manoj.

                          Comment

                          • manoj1978@gmail.com

                            #28
                            Re: Please comment on my integer to string code.


                            Phlip wrote:
                            [color=blue][color=green][color=darkred]
                            > >> > i = -i;[/color]
                            > > Will this really cause issue if i is smallest negetive int?[/color]
                            >
                            > Write a test case (one of the assert() lines I pitched that puts in such an
                            > input that you reach this line with the smallest int.[/color]

                            Using C's INT_MIN is okay for C++ or does it have its own way of
                            representing smallest int?

                            Regards,
                            manoj.

                            Comment

                            • Phlip

                              #29
                              Re: Please comment on my integer to string code.

                              manoj1978 wrote:
                              [color=blue]
                              > Using C's INT_MIN is okay for C++ or does it have its own way of
                              > representing smallest int?[/color]

                              A language lawyer will know the exact difference between INT_MIN and the
                              "trait" that Dietmar suggested. In general, you may use the mostly harmless
                              C library things in C++, because C++'s ISO Standard includes the C Library
                              entirely, by reference, hence a compiler must agree on C's and C++'s size of
                              ints.
                              [color=blue]
                              > I tried with that and it is working fine.want to be sure that it is
                              > okay to use that in C++ or does it have any hidden problems.[/color]

                              You are answering around my point.

                              Please write a batch of test cases, like this:

                              assert("16" == printBase(36+6) );
                              assert("A6" == printBase(10*36 +6));
                              assert("FOO" == printBase(15*36 *36 + 25*36 + 36));
                              ...

                              Run them all each time you make the tiniest change to your program. Put
                              another way, only make such tiny changes that all the tests pass after each
                              one. If they fail, use Undo to back out your changes.

                              That is what your professors should teach on the first day of school; it's
                              what your textbooks should cover right after "hello world". All programs
                              need many test cases for every feature. The alternative is always endless
                              debugging.

                              --
                              Phlip
                              http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


                              Comment

                              • manoj1978@gmail.com

                                #30
                                Re: Please comment on my integer to string code.


                                Phlip wrote:
                                [color=blue]
                                > manoj1978 wrote:[color=green]
                                > > I tried with that and it is working fine.want to be sure that it is
                                > > okay to use that in C++ or does it have any hidden problems.[/color]
                                >
                                > You are answering around my point.
                                >
                                > Please write a batch of test cases, like this:
                                >
                                > assert("16" == printBase(36+6) );
                                > assert("A6" == printBase(10*36 +6));
                                > assert("FOO" == printBase(15*36 *36 + 25*36 + 36));
                                > ...
                                >
                                > Run them all each time you make the tiniest change to your program. Put
                                > another way, only make such tiny changes that all the tests pass after each
                                > one. If they fail, use Undo to back out your changes.[/color]

                                I have to run it for all integers to make sure that in this code,it
                                will never cause problems.
                                But a person who know C++ well can immediately tell, if I reverse part
                                of a string like this,then it will cause issues or will work always.I
                                really want opinion on the language features I used more than the
                                algorithm,input or output.[color=blue]
                                >
                                > That is what your professors should teach on the first day of school; it's
                                > what your textbooks should cover right after "hello world". All programs
                                > need many test cases for every feature. The alternative is always endless
                                > debugging.[/color]

                                Regards,
                                manoj.

                                Comment

                                Working...