holasz
holasz

Reputation: 153

Convert input to int regardless user input

I have the following c code and want to make sure that even though the user enters a float, this will be converted to int.

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

int main()
{
  int i, times, total;
  float average = 0.0;
  int * pArr;

  printf("For how many numbers do you want the average calculated?\n");

  scanf("%d", &times);

  pArr = (int *) malloc(times * sizeof(int));

  printf("Please enter them down here\n");

  for(i=0;i<times;i++) {
    scanf("%d", &pArr[i]);
    total += pArr[i];
  }

  average = (float) total / (float) times;
  printf("The average of your numbers is %.2f\n", average);

  return 0;
}

So the problem here now is that when the user enters a float, the program terminates. Any clue?

Upvotes: 2

Views: 122

Answers (2)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

scanf will stop scanning when it encounters a dot. So direct scanning of input isn't possible.

But you can workaround it by scanning a string, then scanning the integer from your string. That's poor error checking but at least it drops the float part and you can enter floats or integers (also note that total wasn't initialized, and gcc -Wall -Wextra doesn't even detect that).

Find a working version below (would need more error checking when entering integers though):

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

int main()
{
  int i, times, total = 0;  // don't forget to initialize total to 0 !!!
  float average = 0.0;
  int * pArr;
  char temp[30];
  printf("For how many numbers do you want the average calculated?\n");

  scanf("%d", &times);

  pArr = malloc(times * sizeof(int)); // don't cast the return value of malloc

  printf("Please enter them down here\n");

  for(i=0;i<times;i++) {
    scanf("%29s",temp);   // scan in a string first
    sscanf(temp,"%d", &pArr[i]);  // now scan the string for integer
    total += pArr[i];
  }

  average = (float) total / (float) times;
  printf("The average of your numbers is %.2f\n", average);

  free(pArr);  // it's better to free your memory when array isn't used anymore
  return 0;
}

Notes:

  • the array allocation & storage isn't useful here if you only compute the average of the values)
  • you're not protected against a valid floating point exponent input: if 1e10 is entered, the value 1 is scanned (as opposed to "%f" method of the other answer that would work, but that I fear has a risk rounding error)

Upvotes: 3

user9614249
user9614249

Reputation:

If you don't want the user input to be rounded to the nearest int you can simply read it in as a float and then cast to an int.

float in = 0.0f;
scanf("%f", &in);   // Read as float
pArr[i] = (int) in; // Cast to int

Upvotes: 1

Related Questions