Search code examples
cbreak

How can I make sure that my char is not a negative number


I want my for loop to break if -1 is entered but that doesn't seem to work in this case. I've tried it a few different ways but nothing seems to make it actually break.


struct employee{
    char name[30];
    float rate;
    float hrsWorked;
};

int main()
{
    struct employee staff[5];
    int placeholder;
    for(int i = 0; i < 5; i++){
        printf("Enter name: ");
        scanf("%d", &placeholder);
        fgets(staff[i].name, sizeof(staff[i].name), stdin);
       
        if (staff[i].name[0] == -1){
            break;
        }
    }
}

Solution

  • You are storing a string of characters in name, so - and 1 are two different characters.

    This should work:

    if (staff[i].name[0] == '-' && staff[i].name[1] == '1') break;