Thread: converting a string to an array

  1. #16
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by curlyfries
    Look good?
    Unfortunately, no
    • main should be declared as returning int
    • Indent your code properly
    • number should have 6 characters: 1 for the null terminator
    • To avoid buffer overflow, "%s" should be "%5s"
    • Avoid the use of magic numbers (hence my suggestion of '0' instead of 48).
    • Optional, if you are too new: use a loop to loop over num[0] to num[4].

    Note that you do not need to #include<string.h> in this program.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  2. #17
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by curlyfries View Post
    Sweet, I just got it to work. Look good?

    Code:
    #include<stdio.h>
    #include<string.h>
    
    char main(void)
    {
    char number[5];
    printf("Enter a 5 digit number\n");
    printf("XXXXX\n");
    scanf("%s",number);
    
    int num[5];
    num[0]=(number[0]-48);
    num[1]=(number[1]-48);
    num[2]=(number[2]-48);
    num[3]=(number[3]-48);
    num[4]=(number[4]-48);
    
    return 0;
    }
    As for checking to see if the numbers are between 0 and 9, I was thinking of making a simple function that will contain a while loop that checks to see if num[0]-num[4] are between 0 and 9. Will that work?
    Dave
    Hi Dave,
    I see laserlight already gave her critique which is correct as always...

    A couple of things...

    Move the declaration of num[5] above the first printf. It's more about form than substance but I always like to keep the declarations together and generally I comment what they are for...
    Code:
    int main(void)
      { char strnum[6];     // number as string from user
         int num[5];        // converted digits
         int x;             // loop counter
       ....
    It probably won't make whit of difference for such a small program but when you've written code you have to come back to in 5 years, it makes all the difference in the world. Form good habits early.

    Further down you can save yourself some trouble using a loop instead of converting each digit separately...
    Code:
    for ( x = 0; x < strlen(strnum);x++)
      { num[x] = strnum[x] - '0'; }
    Hint: Loops are our friends.

    For the range checking...
    Code:
    for x = 0; x < strlen[number]; x++ )
       { num[x] = number[x] - '0';
           if (num[x] < 0 || num[x] > 9)
             {printf("Digit %d is not acceptable",x);
               num[x] = 0; } }
    Ok... you have to know I didn't just hand you the answer...
    Find the bugs and let us know how you make out...

  3. #18
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Another thing scanf can do is to restrict the input with a regex, so for numeric input restricted to 5 digits this should work.

    Code:
    scanf("%5[0-9]s", str);

  4. #19
    Registered User
    Join Date
    Nov 2010
    Posts
    5
    That works perfectly
    Let me know what you guys think!

    Code:
    {
        char number[6];
        int num[6];
        int x;
    
        printf("enter a 5 digit number\n");
        printf("XXXXX\n");
        scanf("%s",number);
    
        while (strlen(number)!=5)
        {
            printf("the input number must be 5 digits long");
            printf("please re-enter the number\n");
            printf("XXXXX\n");
            scanf("%s",number);
        }       
    
        for (x = 0; x < strlen(number); x++ )
        { 
            num[x] = number[x] - '0';    
            if (num[x] < 0 || num[x] > 9)
            {
                x=(x+1);
                printf("Digit %d is not acceptable\n",x);
                num[x] = 0;
                printf("please re-enter the number\n");
                printf("XXXXXn");
                scanf("%s",number);       
            } 
        }
    
        for ( x = 0; x < strlen(number);x++)
        {
        num[x] = number[x] - '0';
        }
    
            //just a test
        printf("\n");
        printf("\n");
        printf("%d",num[0]);
        printf("%d",num[1]);
        printf("%d",num[2]);
        printf("%d",num[3]);
        printf("%d",num[4]);
        printf("\n");
    
        return 0;
    }
    Thanks,
    Dave
    Last edited by curlyfries; 11-12-2010 at 05:11 PM.

  5. #20
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    The only posible bug would be in the section where you check the converted digits...

    Code:
        for (x = 0; x < strlen(number); x++ )
        { 
            num[x] = number[x] - '0';    
            if (num[x] < 0 || num[x] > 9)
            {
                x=(x+1);                                <------
                printf("Digit %d is not acceptable\n",x);
                num[x] = 0;
                printf("please re-enter the number\n");
                printf("XXXXXn");
                scanf("%s",number);       
            } 
        }
    Incrementing x at that point would displace your replacement digit by one slot in the array.

    Your better plan would be to use scanf() to replace number[x] and decrement x. When the loop resumes it would see the replacement digit and process it as part of the original array.

    Also you have some redundent code in there... you might want to clean it up a bit.
    Last edited by CommonTater; 11-13-2010 at 01:27 AM.

  6. #21
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    Quote Originally Posted by curlyfries View Post
    char main(void) <-- horrible!
    Code:
    int main()
    {
    int i,num[5];
    printf("Enter a 5 digit number\n");
    printf("XXXXX\n");
    scanf("%1d%1d%1d%1d%1d",&num[0],&num[1],&num[2],&num[3],&num[4]);
    for( i=0;i<5;++i )
      printf("\nnum[%d]=%d %s",i,num[i],num[i]>=0&&num[i]<=9?"OK":"error");
    return 0;
    }

  7. #22
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by BillyTKid View Post
    Code:
    int main()
    {
    int i,num[5];
    printf("Enter a 5 digit number\n");
    printf("XXXXX\n");
    scanf("%1d%1d%1d%1d%1d",&num[0],&num[1],&num[2],&num[3],&num[4]);
    for( i=0;i<5;++i )
      printf("\nnum[%d]=%d %s",i,num[i],num[i]>=0&&num[i]<=9?"OK":"error");
    return 0;
    }
    I think you missed the point of the exercise...
    To convert a numeric string to an array of integers...

  8. #23
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    I think you missed the point of the exercise...

  9. #24
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by BillyTKid View Post
    I think you missed the point of the exercise...
    this is an example of what I want...

    user inputs 14364 as a string (scanf("%s",number))

    The number then gets stored in an array like this

    int number[5];

    number[0]=1
    number[1]=4
    number[2]=3
    number[3]=6
    number[4]=4
    Nope, don't think so.

  10. #25
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198
    I see laserlight already gave her critique which is correct as always...

    A couple of things...
    Per K & R 2nd ed., "It's bad practice to bury 'magic numbers' in a program; they
    convey little information to someone who might have to read the program later, and
    they are hard to change in a systematic way."

    One suggestion given, in dealing with "magic numbers" is to give them meaningful
    names for example, using a #define statement.

    I believe the above is the correct concept, not to be taken lightly.

  11. #26
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Char*Pntr View Post
    Per K & R 2nd ed., "It's bad practice to bury 'magic numbers' in a program; they
    convey little information to someone who might have to read the program later, and
    they are hard to change in a systematic way."

    One suggestion given, in dealing with "magic numbers" is to give them meaningful
    names for example, using a #define statement.

    I believe the above is the correct concept, not to be taken lightly.
    Yep... #define is the way to do things in that case.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  4. Converting to expression to string of array elements
    By Sailors in forum C Programming
    Replies: 12
    Last Post: 07-26-2007, 03:01 PM
  5. help converting a char array to a string object?
    By axlton in forum C++ Programming
    Replies: 4
    Last Post: 07-25-2003, 01:34 PM