1
int main()
{
    float T[100];
    float *pt=T;
    float suma = 0, srednia, zmienna;
    int rozmiar;

    printf("How many numbers would you like to put in: ");
    scanf(" %d", &rozmiar);
    int dzielnik = rozmiar;

    printf("\n Enter the number: \n");
    for(int i = 0;i<rozmiar;i++)
    {
        printf("\n i = %d", i );
        scanf("%99f\n", &zmienna);
        *(pt+i) = zmienna;
    }

    return 0;
}

This is my code. The idea is simple. I have an array; I want to scan how many numbers I want to put into the array and then put numbers into array. I don't know why but scanf ignores the second variable that I put in array.

If I put "2" in first scanf, program wants 3 variables from me.

My output should be like this:

How many numbers would you like to put in: 2 

Enter the number:

i = 0

2 (my number)

i=1

3 (my number)

but it's actually like this:

How many numbers would you like to put in: 2 

Enter the number:

i = 0

1 (my number)

2 (my number)

i = 1

3 (my number)
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ice592
  • 27
  • 2
  • 7
  • 1
    remove the newline from scanf, like so `scanf("%99f", &zmienna);` – sebastian Mar 20 '19 at 21:58
  • 2
    If you are using just `%d` and `%f` you don't need to worry about newlines, leading whitespace gets filtered (`%c` is another matter). But what is the `99` in `%99f` supposed to achieve? Keep it simple, for now. – Weather Vane Mar 20 '19 at 22:04

1 Answers1

2

The specific problem you were having is with scanf: putting a \n is generally a bad idea because entering a newline is generally how you send off a line of characters to the program. Use '\n' liberally in printf and "never" with scanf.

Here's my modified version. I removed the pointer shenanigans because indexing into the array is simpler and better, and also initialized the array which you should always do:

#include <stdio.h>

int main() {
    float T[100] = {0}; // Used to not be initialized.
    float suma = 0, zmienna;
    int rozmiar;

    printf("How many numbers would you like to put in: ");
    scanf("%d", &rozmiar);

    printf("\n Enter the number: \n");
    for (int i = 0; i<rozmiar; i++) {
        printf("\n i = %d", i);
        scanf("%f", &zmienna);
        T[i] = zmienna;
    }

    return 0;
}
AJNeufeld
  • 8,526
  • 1
  • 25
  • 44
brothir
  • 694
  • 6
  • 14