-4

For example, 1st input is "B 2 A 0" press Enter. team1[0] = 'B' and rest of it is addressing True. No problem so far. But in 2nd input this happens.. assume that this is my 2nd input >> "A 1 B 1" team1[1] is not 'A'. as you guessed score1[1] and score2[1] is not 1 either, and that's why im asking.

// the first versions of the arrays 
// 0x7fffffffea60 "p\353\377\377\377\177"    team1[size]
// 0x7fffffffea50 "\240\353\377\377\377\177" team2[size]

// after 1st input ( assume "B 2 A 0" )
// 0x7fffffffea60 "B\353\377\377\377\177"    team1[size]
// 0x7fffffffea50 "A\353\377\377\377\177"    team2[size]

// after 2nd input ( assume "A 1 B 1" )
// 0x7fffffffea60 "B\n\377\377\377\177"      team1[size]
// 0x7fffffffea50 "A\353\377\377\377\177"    team2[size]

char team1[size];
char team2[size];
int score1[size];
int score2[size];

for(i=0;i<size;i=i+1)
{
    scanf("%c %d %c %d",&team[i],&score1[i],&team2[i],&score2[i]);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

1

With

char team1[size];
char team2[size];
int score1[size];
int score2[size];

for(i=0;i<size;i=i+1)
{
  scanf("%c %d %c %d",&team[i],&score1[i],&team2[i],&score2[i]);
}

And as you say

1st input is "B 2 A 0" press Enter.

the enter is not read by your first scanf and is still available, so the second loop the first %c gets it then scanf see A for the first %d and returns without setting score1[1] team2[1] and score2[1]

As said in a remark you can use " %c %d %c %d", that bypasses spaces and newlines at the beginning of the input.

Note you already uses that bypassing putting a space between %d and %c so N 2 A 0 is read as expected

As also said in a remark check the result of scanf valuing 4 when the inputs are ok

#include <stdio.h>

#define size 100

int main()
{
  char team1[size];
  char team2[size];
  int score1[size];
  int score2[size];
  int i, j;

  for(i=0; i < size; ++i)
  {
    if (scanf(" %c %d %c %d", &team1[i], &score1[i], &team2[i], &score2[i]) != 4)
      break;
  }

  /* check */
  puts("input values:");

  for(j=0; j<i ; ++j)
  {
    printf("%c %d %c %d\n", team1[j], score1[j], team2[j], score2[j]);
  }
}

Compilation and execution :

pi@raspberrypi:/tmp $ ./a.out
B 2 A 0
A 1 B 1

   C 22     D13
input values:
B 2 A 0
A 1 B 1
C 22 D 13

(I used the non visible control+d to finish the input)

bruno
  • 32,421
  • 7
  • 25
  • 37