Thread: char extraction

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    39

    Unhappy char extraction

    how can i extract fraction e.g. 12/4 which is stored in a char array?i mean i want to put 12 in int numerator and 4 in int denominator.
    once a kohatian,always a kohatian!

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    probably best to use a struct/class to hold the two separate attributes in a single entity and then store a collection of objects of the user defined struct/class in whatever container you elect to use. I suppose you could consider putting the numerator in even numbered elements and the associated denominator in odd numbered elements, but I have never heard of doing it that way. Might be kinda fun to work it out though. Hmmm........

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    One way is to use function sscanf().
    Code:
    #include <stdio.h>
    #include <iostream>
    
    using namespace std;
    
    int main(void)
    {
       char *str = "12/4";
       int n, d;
    
       sscanf(str,"%d/%d",&n,&d);
    
       cout << str << endl;
       cout << "n:" << n << endl;
       cout << "d:" << d << endl;
       return 0;
    }
    I think you can use <cstdio> in place of <stdio.h>

  4. #4

  5. #5
    Registered User
    Join Date
    Jan 2002
    Posts
    106
    you veterans are making it hard for the rookies.
    Heres a simple program.

    Here:

    #include <iostream.h>
    #include <conio.h>
    #include <conio.c> // I'm using Bloodshed, need this for getch();

    int main()
    {
    int numerator=4;
    int denominator=12;
    cout << numerator << "/ " << denominator << endl;

    getch();
    return 0;
    }

  6. #6
    Registered User Dual-Catfish's Avatar
    Join Date
    Sep 2001
    Posts
    802
    Sure, but he asked how to extract it from a char array.

  7. #7
    Registered User
    Join Date
    Jan 2002
    Posts
    106
    ok, cool

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Sorting Linked Lists
    By DKING89 in forum C Programming
    Replies: 6
    Last Post: 04-09-2008, 07:36 AM
  3. Need help understanding info in a header file
    By hicpics in forum C Programming
    Replies: 8
    Last Post: 12-02-2005, 12:36 PM
  4. Need help fixing bugs in data parsing program
    By daluu in forum C Programming
    Replies: 8
    Last Post: 03-27-2003, 06:02 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM