Homework 1 Part 3 - Dealing with the Fractional Part

For Part 3, you'll read the fractional part as a string and then process each of the characters in the string as the digits they represent.

That's why the 2nd format is %s (for a string), as in:

%d.%s

Creating a String

To start, you need to declare a string in your main function:
char fract[80];

As you can see, a string in this case is declared as an array of characters. Make sure that you provide enough characters in this array for the fractional part (80 should be plenty).

Reading in the String

Next, you need to read the fractional part into this string. If you were just reading in that part, you would do something like:
scanf("%s", fract);

Note that you don't put an ampersand (&) in front of a string when you scan it in (unlike other types of variable).

Of course, you'll probably be scanning in the integral and fractional part in one scanf, so the above will have to be changed to reflect that.

Processing the String

Finally, to go through each character of the string, you can use the following loop construct:
int i;  /* Put this at beginning of function. */

for (i = 0; fract[i] != '\0'; i++) {
   int digit;
   digit = fract[i] - '0';
   /* Use the digit. */
}

Note that we access a specific character in the string with fract[i] (i.e., access the ith one). We know we are at the end of the string when we hit the '\0' (i.e., the nul character, represented by the "backslash zero" in single quotes). Since fract[i] gives the character and we want its numeric value, we convert it to the proper digit (0/1) by subtracting '0' (with the single quotes, this is the character zero, not the number zero).