0

I was trying to make a currency converter using C language and it was really easy to do, but I was trying to readjust it by using functions because I wanted to rewrite the code each time the user enters a wrong input. Here's my code:

#include <stdio.h>
char conv;
int convert()
{
    if (conv == 'd')
    {
        float i;
        printf("type the amount in dollars: ");
        scanf("%f", &i);
        float egp = i * 15.72;
        printf("Your amount in egp is: %.2f", egp);
    }
    else if (conv == 'e')
    {
        float i;

        printf("type the amount in egyptian: ");
        scanf("%f", &i);
        float egp = i / 15.72;
        printf("Your amount in dollars is: %f", egp);
    }
    return 0;
}

int error()
{
    return main();
}

int main()
{
    printf("\nPlease write {d} to converts dollars to egp, type {e} to convert egp to dollars: ");
    scanf("%c", &conv);
    if (conv == 'd' || conv == 'e')
    {
        convert();
    }
    else
        error();

    return 0;
}

It works like a charm because I spent a good amount of time on it, but the thing is it rewrites the code twice; I don't know what's causing this, I'm pretty sure there's something missing in my function logic and my understanding of functions in c. Go ahead try it out.

WhozCraig
  • 63,603
  • 10
  • 71
  • 134
Younis
  • 17
  • Welcome to SO. Please take a few moments to apply some decent formatting to your code. Proper indentation is important for readability. Especially for beginners that is vital. – Gerhardh Jan 09 '22 at 00:20
  • 1
    `return main();` is a bad idea. I've leaned that it is allowed to call `main` in C, but it's more often than not a mistake. – Ted Lyngmo Jan 09 '22 at 00:20
  • I agree with Ted Lyngmo. If you need to call `main` inside your program, you are doing something wrong. You should be able to use loops and control structures to handle your needs without calling `main`. – Gerhardh Jan 09 '22 at 00:23
  • You should always check return value of `scanf` and friends. – Gerhardh Jan 09 '22 at 00:31
  • If the `error()` function calls `main()` then `scanf("%c", &conv);` will read the previous newline left in the buffer. Use `scanf(" %c", &conv);` with a space. This FAQ about `scanf` behaviour gets asked several times every day, year after year. – Weather Vane Jan 09 '22 at 00:34
  • Aside: please try to avoid the use of global variables. `char conv;` should really be a local variable in `main()`, and passed to `int convert(char conv)`. – Weather Vane Jan 09 '22 at 00:39
  • 1
    Better to use `double`, (in units of cents), but if stuck with `float`, might as well use `float` math: `float egp = i * 15.72;` --> `float egp = i * 15.72f;` (add f) – chux - Reinstate Monica Jan 09 '22 at 00:41

0 Answers0