1

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;
        }
    }
}
Fuss
  • 13
  • 3
  • Do you want to break if the number negative one is entered? Or do you want to break if a "-" followed by a "1" is entered? They are different things. For example, the former also breaks on "-01" and the latter does not. – David Schwartz Jul 07 '22 at 03:53
  • 1
    it's a misleading interface to prompt the user for a name (implies a string), then read in an `int`. _If_ you're going to do that, might as well `if (placeholder==-1) break;` before `fgets`ing for the name. But [mixing `scanf` and `fgets` is generally frowned upon](https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf) and can lead to unexpected behavior. Better to get all the input as a string and parse for what you're looking for. – yano Jul 07 '22 at 04:25
  • 1
    Why wouldn't you have the user just press Enter to end? `-1` is so arbitrary! If instead entering a blank line finishes the loop, your code is cleaner and the interface is more intuitive. – paddy Jul 07 '22 at 04:27

3 Answers3

3

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;
ificiana
  • 98
  • 7
1

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] : -, where 45 is the ASCII value, and name[1] : 1.

To solve this issue, you could do this:

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

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

  • 3
    Please do _not_ recommend hard-coding ASCII constants instead of character literals. It's perfectly fine to use use `== '-'` and `== '1'`. Don't create unnecessary problems when you write code. In this case, your approach is less readable and less portable. – paddy Jul 07 '22 at 04:25
  • Good point, was just trying to highlight the connection between ASCII and character literals. – RagingMonkey Jul 07 '22 at 15:25
0

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;
}
Sidharth Mudgil
  • 1,293
  • 8
  • 25