#scanf and fgets

12 messages · Page 1 of 1 (latest)

zealous epoch
#

I need to get a position using scanf and a string line from the user using fgets but fgets doesn't work

I thought the issue is a \n in the scanf automatically create it after your input

I coded scanf("%i\n", &n) but it still didn't work

int inputPosition(){
  int n = -1;
  printf("Input a position (you have %i elements):\n", numElements);

  while(1){
    scanf("%i\n", &n);
    if (n < 0 || n > numElements){
      printf("Invalid input! Please, try again\n");
    } else {  
      break;
    }
  }
  return n;
}

struct node *newNode(){
  
  struct node *newNode = malloc(sizeof(struct node));
  if (newNode == NULL){
    printf("malloc's error");
    return NULL;
  };

  printf("input your data:\n");
  fgets(*newNode->data, N, stdin);

  newNode->prev = NULL;
  newNode->next = NULL;

  return newNode;
}
warm fossilBOT
#

@zealous epoch

It looks like you may have code formatting errors in your message

Note: Make sure to use back-ticks (`) and not quotes (')
Note: Make sure to specify a highlighting language, e.g. `cpp`, after the back-ticks

Markup

```c
int main() {}
```

Result
int main() {}
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

jade robin
#

a whitespace character (such as \n) in a scanf string means it will keep reading data until it finds a non-whitespace character

#

also scanf returns whether or not it successfully read an integer via its return value, if it returned 1 here it read the integer

#

anything else then it failed

#

IMO the solution here is to ditch scanf, read each line with fgets instead

#

and strtol to read the integer

zealous epoch
zealous epoch
warm fossilBOT
#

@zealous epoch Has your question been resolved? If so, type !solved :)

zealous epoch
#

!solved