-1

I'm working with a project, but I can't find a way to store float numbers in a array. I have a .txt file (testfile.txt) with float numbers, like this

1.0 2.0
3.0 4.0
5.0 6.0
7.0 8.0
9.0 10.0

And I want to store it into a array. But when I do this, all my numbers are converted to integers. My program looks like this:

#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    double number[10];

    ifstream infile;
    infile.open("testfile.txt");
    for(int a=0; a<10; a=a+1)
    {
      infile >>  number[a]; // Reading from the file
      cout << number[a] << endl;
    }
}

And the output is like this

1
2
3
4
5
6
7
8
9
10

Can someone please explain to me what I'm doing wrong? I have tried a lot, thanks in advance!

nordhagen
  • 59
  • 1
  • 7
  • Can you explain where the problem is?? – Amit Aug 27 '16 at 22:43
  • "*all my numbers are converted to `float`*" -- I'm assuming here that you really mean you think all numbers are converted to `int` as they're printed "as integers" in the output. If my assumption here is correct, then you're just not setting the `std::ostream` precision such that they would be printed with decimals - the numbers themselves are stored as `double` indeed. – sjrowlinson Aug 27 '16 at 22:45
  • 3
    You can use `std::fixed` and [`std::setprecision()`](http://en.cppreference.com/w/cpp/io/manip/setprecision) to control the output of decimal digits. – πάντα ῥεῖ Aug 27 '16 at 22:45
  • Hi nordhagen, and welcome to Stack Overflow. I don't quite understand your question; all the numbers in the input file are integers, and the output you show seems to be preserving the number values perfectly. What were you expecting to happen differently? – Vince Bowdren Aug 27 '16 at 22:46

1 Answers1

2

Your problem is not how you store the numbers.

The numbers get stored just fine.

Your problem is how you view the numbers.

The way you print the numbers is wrong, so the numbers that you see are wrong, so you think there is something wrong with the numbers.

By default, cout << my_double_variable will render your double without decimals.

A simple google search for "C++ cout double" yields as first result the following stackoverflow Q&A:

How do I print a double value with full precision using cout?

According to which, the solution is to use cout.precision(N); where N is your desired precision.

The little print: If you were using a debugger you would have seen this for yourself, without the need to write any code to print stuff, without being misled by the wrong printouts, and without all the wild goose chasing. So, my advice is: start using a debugger..

Community
  • 1
  • 1
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142