Thread: Convert char array to int

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    5

    Convert char array to int

    Hey guys, I'm having a problem with converting characters from a char array to int variables. I've searched over the forums but haven't been able to find an answer. What I'm trying to do is write a program that adds two fractions, where the fractions will be entered in by the user as 1/8 or 12/10 for example.

    The code below works fine for single digit fractions (eg: 1/8) but I cant get it to work for double digit ones.

    Here's what I have so far:

    Code:
     printf("Enter fraction #1: ");
       fgets(fractionOne, FR_MAX_INPUT+1, stdin);
    
       /* test to makesure that we have ALL of the line */
       if(fractionOne[strlen(fractionOne) - 1] != '\n') {
          /* the newline must be in the buffer */
          readRestOfLine();
       } else { /* get rid of the new line from the input */
          fractionOne[strlen(fractionOne) - 1] = '\0';
       }
    
       origFracOneNumerator = atoi (fractionOne);
       origFracOneDenominator = atoi (fractionOne+2);
    Now I thought it would be simply a matter of changing the line
    Code:
    origFracOneDenominator = atoi (fractionOne+2);
    to
    Code:
    origFracOneDenominator = atoi (fractionOne+3);
    But when I do this it tells me the value of origFracOneDenominator is 0 and not the second half of the fraction.

    Any ideas?

    Thanks in advance!

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Your job would be a lot easier if you used sscanf() or even strtol() instead of atoi(). And I'd recommend switching functions anyway, because atoi() doesn't do any error checking.

    strtol() can set a pointer to the character beyond the number it processed, which you can then increment until you pass a '/', then you can call strtol() again. Something like
    Code:
    char f[] = "12/34";
    char *p;
    long x, y;
    x = strtol(f, &p, 0);
    while(isspace(*p || *p == '/')) p ++;
    y = strtol(p, NULL, 0);
    With sscanf(), you can use
    Code:
    char f[] = "12/34";
    int x, y;
    if(sscanf(f, "%d/%d", &x, &y) != 2) { /* error */ }
    For more information, see
    http://www.cplusplus.com/reference/c...ib/strtol.html
    http://www.cplusplus.com/reference/c...io/sscanf.html
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Jul 2007
    Posts
    5
    Thanks for that. I've only been programming C for about 8 weeks so I'm still a little unsure on what functions are best to use and when.

    Will give strtol a try and let u know how it goes.

    Thanks again.

  4. #4
    Registered User
    Join Date
    Jul 2007
    Posts
    5
    Hmm, that seems to be doing the same thing. When I type in 12/13 it tells me x is 12 and y is 0.

    Am I missing something here?

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Post your latest code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Jul 2007
    Posts
    5
    Code:
    char fractionOne[FR_MAX_INPUT+1];
       char fractionTwo[FR_MAX_INPUT+1];
       char *p;
       long x, y;
    
       printf("Fractions\n");
       printf("------------------\n");
    
       printf("Enter fraction #1: ");
       fgets(fractionOne, FR_MAX_INPUT+1, stdin);
    
       /* test to makesure that we have ALL of the line */
       if(fractionOne[strlen(fractionOne) - 1] != '\n') {
          /* the newline must be in the buffer */
          readRestOfLine();
       } else { /* get rid of the new line from the input */
          fractionOne[strlen(fractionOne) - 1] = '\0';
       }
    
       x = strtol(fractionOne, &p, 0);
       while(isspace(*p || *p == '/')) p ++;
       y = strtol(p, NULL, 0);
    
       printf("x is %d\n: ", x);
       printf("y is %d\n: ", y);

  7. #7
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    isspace(*p || *p == '/')
    shouldn't it be
    Code:
    isspace(*p) || *p == '/'
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  8. #8
    Registered User
    Join Date
    Jul 2007
    Posts
    5
    Nah, I thought that at first but it still produces the same output.

  9. #9
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    There won't necessarily be a newline on the end of text entered into stdin, the FAQ demonstrates a good method on determining if there is - and to remove it if it's there.

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Works for me - note the change to the printf's at the end.
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    #define FR_MAX_INPUT 100
    
    int main ( void ) {
       char fractionOne[FR_MAX_INPUT+1];
       char *p;
       long x, y;
    
       printf("Fractions\n");
       printf("------------------\n");
    
       printf("Enter fraction #1: ");
       fgets(fractionOne, FR_MAX_INPUT+1, stdin);
    
       /* test to makesure that we have ALL of the line */
       if(fractionOne[strlen(fractionOne) - 1] != '\n') {
          /* the newline must be in the buffer */
          /*readRestOfLine();*/
       } else { /* get rid of the new line from the input */
          fractionOne[strlen(fractionOne) - 1] = '\0';
       }
    
       x = strtol(fractionOne, &p, 0);
       while( isspace(*p) || *p == '/' ) p ++;
       y = strtol(p, NULL, 0);
    
       printf("x is %ld\n", x);
       printf("y is %ld\n", y);
       return 0;
    }
    
    $ ./a.exe
    Fractions
    ------------------
    Enter fraction #1: 12/34
    x is 12
    y is 34
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converted from Dev-C++ 4 to Dev-C++ 5
    By Wraithan in forum C++ Programming
    Replies: 8
    Last Post: 12-03-2005, 07:45 AM
  2. Need help understanding info in a header file
    By hicpics in forum C Programming
    Replies: 8
    Last Post: 12-02-2005, 12:36 PM
  3. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM