0

Experts in this program I am trying to add a sub-string in a main string at the desired position. But the problem is that when I compile it, it first asks me to enter the main string. After I enter the main string, it doesn't ask me to enter the sub-string and directly and directly asks me to enter the position. I don't understand why because syntactically it seems right to me. Please help. Thanks.

#include <stdio.h>
#include <string.h>

int len1, len, n;

void add(char x[25], char y[25], int z, int r) {
  int i;

  for (i = 0; i < z; i++) {
    if (i == r)
      printf("%s", y);
    printf("%c", x[i]);
  }
}

void main() {
  char s[25], q[25];
  int i;

  printf("\nEnter the main string\n");
  scanf("%[^\n]", s);
  len = strlen(s);
  printf("\nEnter the sub-string\n");
  scanf("%[^\n]", q);
  printf("\nEnter the position\n");
  scanf("%d", &n);
  add(s, q, len, n);
}

Also I'd like to add that when I replace the first scanf() by gets(s); and leave the rest of the program as it is, the program is working fine. But it doesn't work well when I use 2 scanfs().

Stargateur
  • 24,473
  • 8
  • 65
  • 91
SGG
  • 31
  • 1
  • 2
  • 8
  • 1
    `'\n'` is never discard so your second string is empty. – Stargateur Nov 05 '17 at 07:42
  • Exactly what are you entering as input and what do you expect as output? – jwdonahue Nov 05 '17 at 07:48
  • `fgets` reads the newline, but `scanf` does not. So the second string entry immediatelty stops at the newline still present in the input buffer. Then the third `scanf` with `%d` format: that filters out leading whitespace. Change the second `scanf` to `scanf(" %[^\n]", q);` notice the added space. – Weather Vane Nov 05 '17 at 07:56
  • Note that [`gets()` is too dangerous to be used — ever!](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used). – Jonathan Leffler Nov 05 '17 at 07:57

0 Answers0