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;
    }
8
  • 1
    atoi Commented Jul 15, 2018 at 5:12
  • Why "-1" in a string field? Why not just an empty string? if (!strlen(name)) Commented Jul 15, 2018 at 5:16
  • It is sadly a part of assignment, but thank you for teaching another function. Commented Jul 15, 2018 at 5:19
  • 2
    You can not compare strings with ==, and you can not compare strings to numbers. Use atoi() to convert a string to integer, or use strcmp() with "-1" (string representation of -1). Commented Jul 15, 2018 at 5:20
  • Thank you for the help. i will try both methods Commented Jul 15, 2018 at 5:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.