Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- bool isValidInput(const int numArgsNeeded, const int numArgsRead, const bool isLastElementOnLine) {
- char lastCharacterOnLine;
- bool correctFormat = (numArgsRead == numArgsNeeded);
- if(isLastElementOnLine) {
- scanf("%c", &lastCharacterOnLine);
- correctFormat = correctFormat && lastCharacterOnLine == '\n';
- }
- return correctFormat;
- }
- char getValidChar(const bool isLastElementOnLine) {
- const int numArgsNeeded = 1;
- int numArgsRead;
- char theCharacter;
- numArgsRead = scanf(" %c", &theCharacter);
- if(isValidInput(numArgsNeeded, numArgsRead, isLastElementOnLine)) {
- return theCharacter;
- }
- else {
- printf("Invalid formatting. Ending program.\n");
- exit(0);
- }
- }
- double getValid(const bool isLastElementOnLine) {
- const int numArgsNeeded = 2;
- int numArgsRead;
- double tempValue;
- char tempUnit;
- numArgsRead = scanf("%lf %c", &tempValue, &tempUnit);
- if(isValidInput(numArgsNeeded, numArgsRead, isLastElementOnLine)) {
- return tempValue && tempUnit;
- }
- else {
- printf("Invalid formatting. Ending program.\n");
- exit(0);
- }
- }
- char getNewUnit(const bool isLastElementOnLine) {
- const int numArgsNeeded = 1;
- int numArgsRead;
- char newUnit;
- numArgsRead = scanf(" %c", &newUnit);
- if(isValidInput(numArgsNeeded, numArgsRead, isLastElementOnLine)) {
- return newUnit;
- }
- else {
- printf("Invalid formatting. Ending program.");
- exit(0);
- }
- }
- int main() {
- char conversionChoice = 0;
- char newUnit = 0;
- double originalValue = 0;
- printf("Pick the type of conversion that you would like to do.\n");
- printf("T or t for temperature\n");
- printf("D or d for distance\n");
- printf("Enter your choice: ");
- conversionChoice = getValidChar(true);
- if (conversionChoice == 'T' || conversionChoice == 't') {
- printf("Enter the temperature followed by its suffix (F, C, or K): ");
- originalValue = getValid(true);
- printf("Enter the new unit type (F, C, or K): ");
- newUnit = getNewUnit(true);
- }
- else if (conversionChoice == 'D' || conversionChoice == 'd') {
- printf("Enter the distance followed by its suffix (I,F,Y,M): ");
- originalValue = getValid(true);
- printf("Enter the new unit type (I,F,Y,M): ");
- newUnit = getNewUnit(true);
- }
- else {
- printf("Unknown conversion type %c chosen. Ending program.", conversionChoice);
- exit(0);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement