0

Here is a code snippet I've been working on. Note that the MAX macro is already defined. It's supposed to ask for the number of teams and then ask for the names of the teams separated by space.

  int num;
  char s[MAX];

  printf("Enter the number of teams\n");
  scanf("%d",&num);
  printf("Enter the team names separated by space");
  scanf("%[^\n]%*c",s);

The second scanf() which I have specified scanset character doesn't take input but directly goes on to execute the rest of the code, resulting in errors.

Here is the output. Note the 4th line is blank, as I can't enter any string and the program executes ignoring the scanf() statement.

Enter the number of teams
5
Enter the teams namenumber of words: 5

str[0]=
str[1]=X
str[2]=╠■`
str[3]=⌡içu$#îu `
str[4]=h_çu

Process returned 0 (0x0)   execution time : 5.265 s

The rest of the code works fine; I think it has something to do with the first scanf() statement as when I remove it, the error doesn't persist.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Aditya Banerjee
  • 352
  • 1
  • 3
  • 12
  • 1
    You can add getchar() between the two scanf functions, so that the second one won't take "enter" as an input – gymni f Jul 06 '17 at 19:42
  • 1
    The `%d` format leaves the newline in the input buffer. The next format rejects the newline as invalid. You need to know that `%c`, `%[…]` (scan sets) and `%n` do not skip white space; all other `scanf()` formats do. You can skip the newline (and an arbitrary number more of them) with `" %[^\n]%*c"`, or you can do line-based input (`fgets()` or similar) and then use `sscanf()` to parse the strings so entered. Also note that you should check the return value from `scanf()` to ensure you got the expected input. – Jonathan Leffler Jul 06 '17 at 19:42

0 Answers0