C: scanf to array

2020-02-29 21:35发布

I'm absolutely new to C, and right now I am trying master the basics and have a problem reading data from scanf straight into an array.

Right now the code looks like this:

int main()
{
    int array[11];
    printf("Write down your ID number!\n");
    scanf("%d", array);
    if (array[0]=1)
    {
        printf("\nThis person is a male.");
    }
    else if (array[0]=2)
    {
        printf("\nThis person is a female.");
    }
    return 0;
}

As you can see, the program's aim is to ask for an ID, and determine from the first number whether the given the person is male(1) or female(2). However it seems I can't get it to work, because the array is not filled properly (this is checked via a printf(array) right after scanf, that results in random numbers). Running the program like this will give the result that the person is a male, no matter what number you read in.

So trivial it may seem, I couldn't figure out the problem.

标签: c
4条回答
手持菜刀,她持情操
2楼-- · 2020-02-29 22:13

Use

scanf("%d", &array[0]);

and use == for comparision instead of =

查看更多
▲ chillily
3楼-- · 2020-02-29 22:18

if (array[0]=1) should be if (array[0]==1).

The same with else if (array[0]=2).

Note that the expression of the assignment returns the assigned value, in this case if (array[0]=1) will be always true, that's why the code below the if-statement will be always executed if you don't change the = to ==.

= is the assignment operator, you want to compare, not to assign. So you need ==.

Another thing, if you want only one integer, why are you using array? You might want also to scanf("%d", &array[0]);

查看更多
Explosion°爆炸
4楼-- · 2020-02-29 22:36
int main()
{
  int array[11];
  printf("Write down your ID number!\n");
  for(int i=0;i<id_length;i++)
  scanf("%d", &array[i]);
  if (array[0]==1)
  {
    printf("\nThis person is a male.");
  }
  else if (array[0]==2)
  {
    printf("\nThis person is a female.");
  }
  return 0;
}
查看更多
干净又极端
5楼-- · 2020-02-29 22:36

The %d conversion specifier will only convert one decimal integer. It doesn't know that you're passing an array, it can't modify its behavior based on that. The conversion specifier specifies the conversion.

There is no specifier for arrays, you have to do it explicitly. Here's an example with four conversions:

if(scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]) == 4)
  printf("got four numbers\n");

Note that this requires whitespace between the input numbers.

If the id is a single 11-digit number, it's best to treat as a string:

char id[12];

if(scanf("%11s", id) == 1)
{
  /* inspect the *character* in id[0], compare with '1' or '2' for instance. */
}
查看更多
登录 后发表回答