Search code examples
c++floating-pointstdio

Program is reading far too many decimal cases


I'm trying to read 3 floats. I tried to do this with floats and doubles, but I get the same behavior with both.

Input example:

3 1 2
32.0 54.7 -2

3 integers on first line, 3 floats on second line:

How I'm reading:

vector<int> order;
vector<double> numbers;
unsigned int order_number;
double number;
char input_character;

while (true)
{
  scanf("%d", &order_number);
  order.push_back(order_number);

  scanf("%c", &input_character);

  if (input_character == ' ')
    continue;
  else
    break;
}

while (true)
{
  scanf("%lf", &number);
  numbers.push_back(number);

  scanf("%c", &input_character);

  if (input_character == ' ')
    continue;
  else
    break;
}

printf("%d %d %d\n", order[0], order[1], order[2]);
printf("%lf %lf %lf\n", numbers[0], numbers[1], numbers[2]);

When printing them, I get:

32.000000 54.700000 -2.000000

I wanted just 32.0, 54.7 and -2. I know I can specify how many decimal places to print with %.x, but I need to print as many as were given to me in the input.

Also, those while (true) loops are there because I don't know how many numbers I'm going to get.


Solution

  • What you want is not possible with plain floating point types. If you want to print the numbers with the same number of decimal places as the input, you have to:

    • Read the input as a string.
    • Parse it yourself and save the number of decimal places.
    • Use that when you print it again.