CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Mar 2009
    Posts
    14

    inputting a fraction in the form x/y

    I want the user to be able to input a fraction in the form "x/y" where x and y are ints and then store the x as a variable numerator and y as a variable denominator. Iv been trying to use cin.gets and ignores but i cant figure this out. I know its probly easy. Thanks for any help.

  2. #2
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,244

    Re: inputting a fraction in the form x/y

    [ Moved thread ]
    Ovidiu
    "When in Rome, do as Romans do."
    My latest articles: https://codexpertro.wordpress.com/

  3. #3
    Join Date
    Jan 2009
    Location
    Salt Lake City, Utah
    Posts
    82

    Re: inputting a fraction in the form x/y

    Read a string from the keyboard
    Search for an occurrence of the character '/'
    Create 2 new strings: one with number before '/' and one with number after '/'
    Convert the 2 new strings to numbers with atoi() or atol() and store them as your object's numerator and denominator, respectively
    Intel Core Duo Macbook w/ Mac OS 10.5.6
    gcc 4.2.1 (i386-apple-darwin9.1.0) and Xcode 3.1.1

  4. #4
    Join Date
    Mar 2009
    Location
    Granada, Spain
    Posts
    40

    Re: inputting a fraction in the form x/y

    Why not:
    Code:
    int x, y;
    char a;
    cin>>x>>a>>y;

  5. #5
    Join Date
    Mar 2009
    Posts
    14

    Re: inputting a fraction in the form x/y

    Quote Originally Posted by Tronfi View Post
    Why not:
    Code:
    int x, y;
    char a;
    cin>>x>>a>>y;
    I want to be able to type for example; 1/2 then press enter. Not have an enter after each entry.

  6. #6
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    Re: inputting a fraction in the form x/y

    Quote Originally Posted by yamahammer342 View Post
    I want to be able to type for example; 1/2 then press enter. Not have an enter after each entry.
    That is what Tronfi's example does.

  7. #7
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: inputting a fraction in the form x/y

    Maybe also try std::getline

    Code:
    string text;
    
    while (getline(cin, text, '/'))
    {
    }
    "It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
    Richard P. Feynman

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured