string --> int[]

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Frank Wagner

    string --> int[]

    Hello NG!

    Though I´m not new to programming at all, i´m new to C++.

    got the following question/problem with it´s behaviour:

    - read number with *arbitrary number of digits* from keyboard (done)
    - then calculate average value and variety of digits

    the second sould be no problem, too, i think.

    the problem is as follows:

    how can i create a int[] from my read string with each element
    representing *one* digit from string?

    i tried this:
    ----------------------------------------
    #include <iostream>
    #include <stdlib.h>
    #include <math.h>
    #include <String.h>

    using namespace std;

    int main(int argc, char *argv[])
    {

    string a;

    cout << "Beliebige Ziffernfolge eingeben" << endl;
    cin >> a;

    int b[sizeof(a)-1];

    for (byte i = 0; i < sizeof(a)-1; i++) {
    b[i] = atoi(&a[i]);
    }

    for (byte i = 0; i < sizeof(a)-1; i++) {
    cout << b[i] << endl;
    }

    cout << endl;
    system("PAUSE") ;
    return 0;
    }
    ----------------------------------------

    doesn´t work! for a="123" i get:
    b[0] = 123
    b[1] = 23
    b[2] = 3

    instead of (what i would need):
    b[0] = 1
    b[1] = 2
    b[2] = 3


    what´s my failure?

    greetings,
    Frank


  • grejdanospam@pacbell.net

    #2
    Re: string --&gt; int[]

    On Wed, 15 Oct 2003 23:03:13 +0200, Frank Wagner
    <newsgroupsspam mails@nofusion. de> wrote:
    [color=blue]
    > Hello NG!
    >
    > Though I´m not new to programming at all, i´m new to C++.
    >
    > got the following question/problem with it´s behaviour:
    >
    > - read number with *arbitrary number of digits* from keyboard (done)
    > - then calculate average value and variety of digits
    >
    > the second sould be no problem, too, i think.
    >
    > the problem is as follows:
    >
    > how can i create a int[] from my read string with each element
    > representing *one* digit from string?
    >
    > i tried this:
    > ----------------------------------------
    > #include <iostream>
    > #include <stdlib.h>
    > #include <math.h>
    > #include <String.h>
    >
    > using namespace std;
    >
    > int main(int argc, char *argv[])
    > {
    >
    > string a;
    >
    > cout << "Beliebige Ziffernfolge eingeben" << endl;
    > cin >> a;
    >
    > int b[sizeof(a)-1];
    >
    > for (byte i = 0; i < sizeof(a)-1; i++) {
    > b[i] = atoi(&a[i]);
    > }
    >
    > for (byte i = 0; i < sizeof(a)-1; i++) {
    > cout << b[i] << endl;
    > }
    >
    > cout << endl;
    > system("PAUSE") ;
    > return 0;
    > }
    > ----------------------------------------
    >
    > doesn´t work! for a="123" i get:
    > b[0] = 123
    > b[1] = 23
    > b[2] = 3
    >
    > instead of (what i would need):
    > b[0] = 1
    > b[1] = 2
    > b[2] = 3
    >
    >
    > what´s my failure?[/color]

    atoi takes const char* and ends conversion when it encounters non digit
    character,

    To convert char to integer - you should just use expression digit -'0'
    b[i] = a[i]-'0';
    instead of atoi in the loop above.

    [color=blue]
    >
    > greetings,
    > Frank
    >
    >
    >[/color]



    --
    grzegorz

    Comment

    • Noah Roberts

      #3
      Re: string --&gt; int[]

      Frank Wagner wrote:
      [color=blue]
      > Hello NG!
      >
      > Though I´m not new to programming at all, i´m new to C++.
      >
      > got the following question/problem with it´s behaviour:
      >
      > - read number with *arbitrary number of digits* from keyboard (done)
      > - then calculate average value and variety of digits
      >
      > the second sould be no problem, too, i think.
      >
      > the problem is as follows:
      >
      > how can i create a int[] from my read string with each element
      > representing *one* digit from string?
      >
      > i tried this:
      > ----------------------------------------
      > #include <iostream>
      > #include <stdlib.h>
      > #include <math.h>
      > #include <String.h>
      >
      > using namespace std;
      >
      > int main(int argc, char *argv[])
      > {
      >
      > string a;
      >
      > cout << "Beliebige Ziffernfolge eingeben" << endl;
      > cin >> a;
      >
      > int b[sizeof(a)-1];
      >
      > for (byte i = 0; i < sizeof(a)-1; i++) {
      > b[i] = atoi(&a[i]);[/color]
      Your failure is here.

      Assuming that a std::string keeps its characters in a byte array (which
      I don't know - experts?)...Wha t you are doing is passing atoi your
      entire string minus the first 'i' characters. Therefor your first
      iteration passes "123", your second "23", your third "3"...and you get
      the results you are seing.

      You could:

      a) Assume that you are working with ASCII and "b[i] = a[i] - '0'". This
      will break on systems that use a character set where 0-9 is not concurrent.
      b) create a char[2] array and fill with a[i], '\0' and pass this to
      atoi....this will always work.

      NR

      Comment

      • Alf P. Steinbach

        #4
        Re: string --&gt; int[]

        On Wed, 15 Oct 2003 23:03:13 +0200, Frank Wagner <newsgroupsspam mails@nofusion. de> wrote:
        [color=blue]
        >Hello NG!
        >
        >Though I´m not new to programming at all, i´m new to C++.
        >
        >got the following question/problem with it´s behaviour:
        >
        >- read number with *arbitrary number of digits* from keyboard (done)[/color]

        Concentrate on the digits, which is a string of characters.

        [color=blue]
        >- then calculate average value and variety of digits[/color]

        Variety?


        [color=blue]
        >
        >the second sould be no problem, too, i think.
        >
        >the problem is as follows:
        >
        >how can i create a int[] from my read string with each element
        >representing *one* digit from string?[/color]


        std::vector<int > v;
        for( std::size_t i = 0; i < s.size(); ++i )
        {
        v.push_back( s[i] - '\0' );
        }



        [color=blue]
        >i tried this:
        >----------------------------------------
        >#include <iostream>
        >#include <stdlib.h>[/color]

        Use
        #include <cstdlib>


        [color=blue]
        >#include <math.h>[/color]

        Use
        #include <cmath>

        [color=blue]
        >#include <String.h>[/color]

        <string.h> is not the same header as <string>




        [color=blue]
        >using namespace std;
        >
        >int main(int argc, char *argv[])
        >{
        >
        > string a;[/color]

        You're unlucky if this compiles (it might, depending on what <vector> drags
        in).


        [color=blue]
        >
        > cout << "Beliebige Ziffernfolge eingeben" << endl;
        > cin >> a;
        >
        > int b[sizeof(a)-1];[/color]

        You need a.size(), not sizeof(a). The former tells you the number of characters
        stored in the string, the latter the size in bytes of the container variable
        (which typically holds just a pointer to the character buffer, plus a few other
        values such as the current length returned by the size() member function).

        [color=blue]
        >
        > for (byte i = 0; i < sizeof(a)-1; i++) {[/color]

        There's no predefined data type 'byte' in standard C++.

        Also, use '++i', not 'i++'.


        [color=blue]
        > b[i] = atoi(&a[i]);[/color]

        'atoi' expects a zero-terminated string of digits, which you're giving
        it, namely a[i] and all following characters until the terminating zero...


        [color=blue]
        > }
        >
        > for (byte i = 0; i < sizeof(a)-1; i++) {[/color]

        See above.

        [color=blue]
        > cout << b[i] << endl;
        > }
        >
        > cout << endl;
        > system("PAUSE") ;[/color]

        This will only work on a system with a "PAUSE" command (e.g. Windows), and
        it will make it slightly more difficult to test the program automatically, or
        to use it in automation.

        [color=blue]
        > return 0;[/color]
        ¨
        OK, but you don't need it (a special feature of 'main' is that it returns 0
        by default).
        [color=blue]
        >}
        >----------------------------------------
        >
        >doesn´t work! for a="123" i get:
        >b[0] = 123
        >b[1] = 23
        >b[2] = 3
        >
        >instead of (what i would need):
        >b[0] = 1
        >b[1] = 2
        >b[2] = 3
        >
        >
        >what´s my failure?[/color]

        That, I don't know... ;-)

        Comment

        • Unforgiven

          #5
          Re: string --&gt; int[]

          Alf P. Steinbach wrote:[color=blue][color=green]
          >> for (byte i = 0; i < sizeof(a)-1; i++) {[/color]
          >
          > Also, use '++i', not 'i++'.[/color]

          Why?

          --
          Unforgiven

          A: Top Posting!
          Q: What is the most annoying thing on Usenet?

          Comment

          • Alf P. Steinbach

            #6
            Re: string --&gt; int[]

            On Thu, 16 Oct 2003 00:22:59 +0200, "Unforgiven " <jaapd3000@hotm ail.com> wrote:
            [color=blue]
            >Alf P. Steinbach wrote:[color=green][color=darkred]
            >>> for (byte i = 0; i < sizeof(a)-1; i++) {[/color]
            >>
            >> Also, use '++i', not 'i++'.[/color]
            >
            >Why?[/color]

            Several reasons, all having to do with good coding practice.

            The most important reason is that "++i" works with most kind of data types
            providing an increment operation, whereas "i++" does not. In particular
            for iterators. So getting used to writing "++i" as default is a good idea.

            The most often encountered reason is that "++i" has a less error-prone
            side-effect than "i++", in other words, is a tad less unsafe.

            The most religious reason is that with "i++" extra work is requested, which
            is only meaningful if that work is contributing towards the code's overall
            purpose; and meaningless code should be avoided.

            The most easily grasped reason, for complete novices (if you have some
            experience this can be very difficult to grasp since it's only technically
            true, not usually relevant to anything), is that "++i" can be more efficient
            than "i++", e.g. see the FAQ §13.12.

            Comment

            • Frank Wagner

              #7
              Re: string --&gt; int[] meets another question...

              Thank you for your help! Did it, but now got another problem:

              if i have:
              int b[3];

              it´s:
              sizeof(b) = 12; // cause sizeof(int) = 4

              but if i do sth like this:
              -----------------------------------
              void my_function(int arr[])
              {
              ....
              sizeof(arr);
              // sizeof(arr) only returns 4!!! what´s happened?
              ....
              }

              void main()
              {
              ....
              int b[3];
              // sizeof(b) returns 12 - so everythings alright...
              my_function(b);
              ....
              }
              -----------------------------------

              there´s inside of my_function:
              sizeof(arr) = 4;

              What´s happening here, and how can i receive the "correct" value for
              sizeof(b) in my functions? ("correct" now means 12 to me ;) )

              thanks for your time!

              greetings,
              Frank

              Comment

              • Alf P. Steinbach

                #8
                Re: string --&gt; int[]

                On Wed, 15 Oct 2003 21:35:00 GMT, alfps@start.no (Alf P. Steinbach) wrote:
                [color=blue]
                > std::vector<int > v;
                > for( std::size_t i = 0; i < s.size(); ++i )
                > {
                > v.push_back( s[i] - '\0' );
                > }[/color]

                Oops, keyboard error: that should be '0' not '\0'.

                Comment

                • Tim Threlfall

                  #9
                  Re: string --&gt; int[]

                  You could also use stringstreams instead of atoi to convert your string
                  into an int, something like this

                  template<typena me RT, typename T, typename Trait, typename Alloc>
                  RT ss_atoi( std::basic_stri ng<T, Trait, Alloc>& the_string )
                  {
                  std::basic_istr ingstream< T, Trait, Alloc> temp_ss(the_str ing);
                  RT num;
                  temp_ss >> num;
                  return num;
                  }



                  Or use boost::lexical_ cast


                  Comment

                  • Ryan Winter

                    #10
                    Re: string --&gt; int[] meets another question...

                    Frank Wagner wrote:[color=blue]
                    > Thank you for your help! Did it, but now got another problem:
                    >
                    > if i have:
                    > int b[3];
                    >
                    > it´s:
                    > sizeof(b) = 12; // cause sizeof(int) = 4
                    >
                    > but if i do sth like this:
                    > -----------------------------------
                    > void my_function(int arr[])
                    > {
                    > ...
                    > sizeof(arr);
                    > // sizeof(arr) only returns 4!!! what´s happened?
                    > ...
                    > }
                    >
                    > void main()
                    > {
                    > ...
                    > int b[3];
                    > // sizeof(b) returns 12 - so everythings alright...
                    > my_function(b);
                    > ...
                    > }
                    > -----------------------------------
                    >
                    > there´s inside of my_function:
                    > sizeof(arr) = 4;
                    >
                    > What´s happening here, and how can i receive the "correct" value for
                    > sizeof(b) in my functions? ("correct" now means 12 to me ;) )[/color]

                    This is always a bit tricky. You have to remember that when you pass an
                    array into a function, you are actually passing a pointer to the array.
                    Therefor when you try and get its size, you end up with the size of the
                    pointer.

                    The way around it is to pass the length of the array in as a second
                    parameter, or even easier, pass it in as a std::vector<int >&.

                    <code>

                    #include <vector>

                    void my_function(std ::vector<int>& arr)
                    {
                    arr.size(); // 3
                    }

                    int main()
                    {
                    std::vector<int > b(3);
                    b.size() // 3

                    my_function(b);
                    }

                    </code>

                    Ryan

                    Comment

                    • Tim Threlfall

                      #11
                      Re: string --&gt; int[]

                      You could also use stringstreams instead of atoi() to convert an
                      std::string into an int, something like this

                      template<typena me RT, typename T, typename Trait, typename Alloc>
                      RT ss_atoi( std::basic_stri ng<T, Trait, Alloc>& the_string )
                      {
                      std::basic_istr ingstream< T, Trait, Alloc> temp_ss(the_str ing);
                      RT num;
                      temp_ss >> num;
                      return num;
                      }


                      Or you could use boost::lexical_ cast.

                      Comment

                      • Gavin Deane

                        #12
                        Re: string --&gt; int[]

                        Noah Roberts <nroberts@donte mailme.com> wrote in message news:<vorels5sk h2ha2@corp.supe rnews.com>...[color=blue]
                        > You could:
                        >
                        > a) Assume that you are working with ASCII and "b[i] = a[i] - '0'". This
                        > will break on systems that use a character set where 0-9 is not concurrent.[/color]

                        I thought that there was a guarantee that subtracting '0' from any
                        char '0', '1', '2', ... '9' had to give the results 0, 1, 2, ... 9,
                        even if those characters were not contiguous in the underlying
                        character set. A few things occur:

                        I can't remember where I got this idea from.

                        I have no idea how it would work when the characters are not
                        contiguous - there would need to be some extra level of interpretation
                        somewhere.

                        I can't find it in the standard, though if it were guaranteed I
                        suppose it could be inherited from the C standard and I don't have
                        that.

                        While I can't think how it would work, I'm still sure I've come across
                        this guarantee somewhere reputable. Can anyone enlighten me?

                        GJD

                        Comment

                        • Karl Heinz Buchegger

                          #13
                          Re: string --&gt; int[]



                          Noah Roberts wrote:[color=blue]
                          >
                          > You could:
                          >
                          > a) Assume that you are working with ASCII and "b[i] = a[i] - '0'". This
                          > will break on systems that use a character set where 0-9 is not concurrent.[/color]

                          The characters '0' to '9' are concurrent in C++ by definition.
                          So there is no problem in using the above. It will work everywhere.


                          --
                          Karl Heinz Buchegger
                          kbuchegg@gascad .at

                          Comment

                          • Karl Heinz Buchegger

                            #14
                            Re: string --&gt; int[]



                            Gavin Deane wrote:[color=blue]
                            >
                            > Noah Roberts <nroberts@donte mailme.com> wrote in message news:<vorels5sk h2ha2@corp.supe rnews.com>...[color=green]
                            > > You could:
                            > >
                            > > a) Assume that you are working with ASCII and "b[i] = a[i] - '0'". This
                            > > will break on systems that use a character set where 0-9 is not concurrent.[/color]
                            >
                            > I thought that there was a guarantee that subtracting '0' from any
                            > char '0', '1', '2', ... '9' had to give the results 0, 1, 2, ... 9,
                            > even if those characters were not contiguous in the underlying
                            > character set. A few things occur:
                            >
                            > I can't remember where I got this idea from.[/color]

                            From the C++ standard. Although not mentioned explicitely
                            in the C++ standard, it follows from other definitions.
                            In C, the above is mentioned explicitely and as far as I know
                            the non-mentioning in C++ is considered a defect in the C++
                            standard and will be corrected.

                            --
                            Karl Heinz Buchegger
                            kbuchegg@gascad .at

                            Comment

                            Working...