Reading fractions in C

后端 未结 6 529
臣服心动
臣服心动 2021-01-14 23:45

How do I read a fraction into C to do math with it? (The fraction will contain the slash symbol) For example, A user will input 3/12. (a string) The program will find the gc

6条回答
  •  渐次进展
    2021-01-15 00:29

    Keep a pointer to the head of the string.

    Then look into using strchr() to get a second pointer that points to the / character.

    You can then:

    1. Read characters from a dereferenced first pointer up until your first pointer is equal to the second pointer. Store those characters into a char [] or char * — that's your numerator as a C string.
    2. Read from the next character after where the second pointer points, up to the /0 nul terminator at the end of the string. Store those characters in a second char [] or char * — that's your denominator as a C string.

    Use atoi() to convert both C strings to integers.

    If strchr() returns NULL, then you can do error checking very easily because there was no / in the input string.

提交回复
热议问题