1

I am a programming noob. I was working on the assignment on my own and i hit the wall right now and any help will be appreciated.

I made loop where i get input for names, rates and hours and if user type -1 it will break the loop and move on to the next loop. Everything is fine except if i type -1 for name it just doesn't break. I know the variable is string and -1 is integer and i just can't figure out what should i do to make this work.

here is part of my stupid code.

for (i = 0; i < size; i++)

{
    puts("\ntype name: (type -1 to quit) \n");
    scanf_s("%s", &name[i], 20);
    puts("\ntype hourly rate: (type -1 to quit) \n");
    scanf_s("%f", &rate[i]);
    puts("\ntype hours worked: (type -1 to quit) \n");
    scanf_s("%f", &hours[i]);
    //if break keyword needed.

    if (*name == -1 || rate[i] == -1 || hours[i] == -1)
    {
        break;
    }
Young KIm
  • 15
  • 3

1 Answers1

0

You could use strcmp() like

scanf_s("%19s", name[i], 20);
if(strcmp(name[i], "-1")==0)
{
    break;
}

strcmp() compares the two strings and returns 0 if both are same.

Leading spaces are not a problem and will be ignored. So -1 will still be read as -1.

Otherwise you could first convert the string in name[i] to an integer and then see if the resultant number is -1. For that approach, see How to convert a string to integer in C?.


Also, if name[i] is a character array of size 20, instead of

scanf_s("%s", &name[i], 20);

you probably need

scanf_s("%19s", name[i], 20);

as name[i] itself is the address since array names decay to pointers to their first element in C.

See this and this.

J...S
  • 5,079
  • 1
  • 20
  • 35