-2

I'm a super beginner programmer. Basically I have got this code:

int main()
{        
    char name[30];
    printf("Name of the animal exchange: \n");
    scanf(" %s", &name);

    char animalname[14];
    int quantity = 0;
    int quantitysum;        
    int type = 1;

    do {        
        printf("A(z) %d. fajta neve: \n", type);                
        scanf(" %s", &animalname);

        while(strlen(animalname)<15) {                                    
            printf("Quantity: \n");
            scanf(" %d", &quantity);
            quantitysum += quantity;
            break;            
        }

        if(strlen(animalname)<15) {
            type++;            
        }        
    } while (animalname != "");
}

I thought the loop was supposed to stop with an enter pressed as stated in the while. What's the problem?

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141

3 Answers3

2

You can't compare strings with !=, since that will only compare the pointers. Instead, you have to use strcmp or a similar function:

while (strcmp(animalname, "") != 0);
Zeta
  • 103,620
  • 13
  • 194
  • 236
0

Use fgets() to get input. %s format specifier won't scan anything when you press just enter whereas fgets does scan it. Also,change

scanf(" %s", &name);

to

scanf(" %s", name);

This is done because the name of an array decays to a pointer to its first element.Replace the below scanf with fgets:

scanf(" %s", &animalname);

Also,string comparision must be done by using strcmp() function from string.h. By using ==,you compare the pointers(Recall that array names decay to a pointer to its first element).Your full code will look like

int main()
{        
    char name[30];
    printf("Name of the animal exchange: \n");
    scanf(" %29s", name); //scan at-most 29 (+1 for the `\0`)

    char animalname[14];
    int quantity = 0;
    int quantitysum=0; //initialize to zero        
    int type = 1;

    do {        
        printf("A(z) %d. fajta neve: \n", type);                
        fgets(animalname,14,stdin);

        if(strlen(animalname)<15) {  //You have a break in the loop which means that you need an if as it will execute just once                 
            printf("Quantity: \n");
            scanf(" %d", &quantity);
            quantitysum += quantity;
            type++; //This can be done here itself
            //break;             
        }

        /*if(strlen(animalname)<15) {
            type++;            
        } This is done in the previous if*/       
    } while (strcmp(animalname,"")!=0);
}

Note that your if will always be true as fgets() limits the amount of characters that it reads. So you can remove it.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

It wont terminate because the condition in the while does not change.....want a c# guide buy thus book http://shoppingict.blogspot.com/2014/12/book-ultimate-c-guide-for-dummies.html?m=1