I am working on a numerology program for a friend of mine. I am trying to implement a simple menu to this program, but it seems to skip the read() function whenever I try the menu. If I don't use a menu, everything's fine. I can't figure out what's wrong.
Code:
/* numer.h */
/* Preprosessor Directives */
#include<stdio.h>
#ifndef NUMER_H
#define NUMER_H
/* Function Declarations */
int convert(char name[], int n);
void read(char str[], int n);
int crunch(int num);
#endif
Code:
/* numer.c*/
/* Preprocessor Directives*/
#include "numer.h"
/* Function Definitions */
/* This function takes a C style string and converts the ascii values of
the letters to what order they are in the english alphabet. Then this
function adds the numbers together and returns that sum.
*/
int convert(char name[], int n)
{
int i, d, sum = 0;
for(i = 0; i<n; i++)
{
if(name[i] <= 90 && name[i] >= 65)
{
d = name[i] - 64;
sum += d;
}
if(name[i] <= 122 && name[i] >= 97)
{
d = name[i] - 96;
sum += d;
}
}
return sum;
}
/* This function takes a C style string and assigns it the name the user
specifies
*/
void read(char str[], int n)
{
char ch;
int i = 0;
while ((ch = getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return;
}
/* This function takes a number and adds the individual digits together
to obtain a single digit. If, when all digits are added together,
the sum is not a single digit, it calls the function again with the
new value. After several recursive calls, it will compute the digit,
then return it.
*/
int crunch(int num)
{
int sum = 0;
while(num != 0)
{
sum += num % 10;
num /= 10;
}
if(sum >= 10)
return crunch(sum);
return sum;
}
Code:
/* numer_driver.c */
/* Preprocessor Directives*/
#include "numer.c"
/* Main Function */
int main() {
/* Variable Declarations */
char name[50];
int j;
for(;;) {
/* Menu */
printf("1. Enter your name\n");
printf("2. Quit\n\n");
printf("Your choice: ");
scanf("%d", &j);
switch (j) {
case 1:
/* Code to enter your name */
printf("Enter your name: ");
read(name, 50);
/* This prints the single digit number your name equals */
printf("\nYour number is %d\n\n", crunch(convert(name, 50)));
break;
case 2:
return 0;
default:
printf("%d is not one of the choices\n\n", j);
break;
}
}
}