C++ – How to store float numbers in array C++

arrayscdoublenumberstext-files

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!

Best Answer

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..