warning: more '%' conversions than data arguments

Viewed 9122

I'm new to C and I'm trying to write a program as an assignment. The user should input 7 floats which will then be stored in an array.

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

int main() {
  float data[32];
  printf("Instert 7 values, separated by spaces: ");
  scanf("%f %f %f %f %f %f %f", data);

  return 0;
}

And I keep getting the error

warning: more '%' conversions than data arguments [-Wformat]
scanf("%f %f %f %f %f %f %f", data);

I tried to look for a solution online but I couldn't figure it out, what am I doing wrong?

3 Answers

This

scanf("%f %f %f %f %f %f %f", data);

should be like this

scanf("%f %f %f %f %f %f %f", &data[0], &data[1], &data[2], &data[3], &data[4], &data[5], &data[6]);

The scanf function requires, for each %-something on the initial string, a pointer to a variable where you'll be storing the input value.

You could alternatively write like this:

scanf("%f %f %f %f %f %f %f", data, data+1, data+2, data+3, data+4, data+5, data+6);

Your array's base memory address/pointer is data. When you sum it with an i where i is a positive integer, you get the pointer to the ith position in the array.

You could use a loop:

for (int i = 0; i < 7; ++i)
    scanf("%f", &data[i]);

With error detection:

#include <stdio.h>
#include <stdlib.h>

// ...

int num_values_read = 0;
for (; num_values_read < 7 && scanf("%f", &data[num_values_read]) == 1;
     ++num_values_read);

if (num_values_read != 7) {
    fputs("Input error :(\n\n", stderr);
    return EXIT_FAILURE;
}

It tells you what is wrong it is just unfortunate that your variable name matches the error messages words. scanf wants a variable for every % there is in the format string. That means in yout example it expects 7 variables but only gets 1.

Related