Search code examples
cwhile-loopfgets

c isalpha and isdigit while loop


How do I put isalpha and isdigit in a while(1) loop?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main()
{
    int i;
    char type[256];
    printf("You can type a number or a word. Type exit to exit! \n");
    printf("Type: ");

    fgets (type, 256, stdin);

    if (isalpha(type[i]))
    {
            printf("Typed text: %s\n", type);
        if((strcmp(type,"exit\n") == 0))
        {
            printf("Exiting...\n");
            exit(1);
        }
    }
    else if (isdigit(type[i]))
    {
            printf("Typed number: %s\n", type);
    }
    else
    {
        printf("Typed: %s\n", type);
        printf("Its not a letter or number...?!\n");
    }
}

I tried adding while(1) at the start at the code and close it at the end of code, but as soon as I enter number or letter the console crashes... Could someone please help me with this?


Solution

  • Your problem is not a loop problem, you need to give a value to i , as it is undefined and you get a nice crash. Please replace

    int i;
    

    with

    int i=0;