1

I want to be able to modify a struct. I have the following.

struct  shopDetails {
    char name[MAX + 1];
};

Then I have the following function which I call from main.

 void modifyShop(struct shopDetails*shopList, int num)
{
char nameInput[MAX + 1];
printf("Name Of Shop You Want To Modify: \n");
fgets(nameInput, sizeof(nameInput), stdin);

char modifyInput[MAX_NAME_LEN + 1];
printf("New Name For Shop: \n");
fgets(modifyInput, sizeof(modifyInput), stdin);
int i = 0;
while (i < num) {
    if (strcmp(shopList->name, nameInput)) {

        //shopList->name = modifyInput;
        return;
    }
    shopList++;
    i++;
}
printf("Couldn't find shop entered.");
}

I am fairly new to C so sorry if this is a bad question but I couldn't find much on it and was wondering why it doesn't allow me use the code that is commented out.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Dan Murphy
  • 225
  • 1
  • 5
  • 15
  • 1
    `fgets` retains any final newline which should be removed. Please see [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221) – Weather Vane Nov 30 '17 at 18:37
  • It looks like you are trying to point shopList->name elsewhere. I think what you want to do is copy the contents of modifyInput to shopList->name. Look at `strncpy`. – Christian Gibbons Nov 30 '17 at 18:41
  • Typo: `fgets(nameInput, sizeof(modifyInput), stdin);` should be `fgets(modifyInput, sizeof(modifyInput), stdin);` Your second input overwrites the first input (as @user3121023 noticed). – Weather Vane Nov 30 '17 at 18:43
  • 1
    Please correct errors mentioned before going further. a) `=` does not copy a string, b) `fgets` retains the newline in the string, c) typo in the second `fgets`. – Weather Vane Nov 30 '17 at 18:48
  • 1
    In addition to the 3 issues of @Weather Vane, `fgets()` needs a buffer 1 larger for maximum input as it may contain a `'\n'`. – chux - Reinstate Monica Nov 30 '17 at 18:52
  • @user3121023 has deleted the comment about confusing `nameInput` and `modifyInput` to which I referred. But latest is good. – Weather Vane Nov 30 '17 at 18:54
  • Possible duplicate of [C assign string from argv\[\] to char array](https://stackoverflow.com/questions/28680557/c-assign-string-from-argv-to-char-array) – melpomene Jan 07 '18 at 20:37

0 Answers0