Find the answer to your Linux question:
Results 1 to 5 of 5
I've searched around and can't find out how to convert a string ( like "12345" ) into an int array ( x[ 5 ] = { 1, 2, 3, 4, ...
  1. #1
    Just Joined!
    Join Date
    May 2010
    Posts
    3

    Lightbulb convert string to int array

    I've searched around and can't find out how to convert a string ( like "12345" ) into an int array ( x[ 5 ] = { 1, 2, 3, 4, 5 } ; ).

  2. #2
    Linux Engineer GNU-Fan's Avatar
    Join Date
    Mar 2008
    Posts
    935
    Debian GNU/Linux -- You know you want it.

  3. #3
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    Quote Originally Posted by GNU-Fan View Post
    While atoi() or strtol() will convert a string into numbers, I think the question was how to convert each letter into an entry in an array of ints.

    Code:
    const char* pStr = "12345";
    size_t len = strlen(pStr);
    int iStr[len];
    
    for (size_t i = 0; i < len; i++)
    {
        iStr[i] = pStr[1] - '0';
    }
    If this is a class problem, consider this your one "freebee".
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

  4. #4
    Linux Newbie
    Join Date
    Apr 2010
    Location
    Novosibirsk, Russia
    Posts
    136
    Quote Originally Posted by Rubberman View Post
    While atoi() or strtol() will convert a string into numbers, I think the question was how to convert each letter into an entry in an array of ints.

    Code:
    const char* pStr = "12345";
    size_t len = strlen(pStr);
    int iStr[len];
    
    for (size_t i = 0; i < len; i++)
    {
        iStr[i] = pStr[1] - '0';
    }
    If this is a class problem, consider this your one "freebee".
    it seems that you should use malloc() after strlen(), not static declaration

  5. #5
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    Actually, the only problem with the code I showed was the loop declaration of the variable 'i' which won't compile with C89, but will with C++. If you move the delcaration out of the loop, then it will compile and run just fine with either a C or C++ compiler.
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...