Home > Software engineering >  How can I make sure that my char is not a negative number
How can I make sure that my char is not a negative number

Time:07-07

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;
        }
    }
}

CodePudding user response:

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;

CodePudding user response:

You can use placeholder to break through the loop

if (placeholder == -1){
   break;
}

You can also use strcmp

NOTE: must include <string.h> header file

if (strcmp(staff[i].name, "-1\n") == 0){
   break;
}

CodePudding user response:

First, name is a char array. So, if name[0] == -1 goes straight to the ASCII representation of a char. Since '-1' is technically 2 characters, they will be separated as such: name[0] : 45, where 45 is the ASCII value, and name[1] : 49.

To solve this issue, you could do this:

    if (staff[i].name[0] == 45 && staff[i].name[1] == 49)

For more info on ASCII, https://www.ascii-code.com/

  • Related