array of doubles from file

I am working on a program that takes a horizontal list of doubles and displays them on the screen, however it doesn't work. I've tried the same thing but with integers and it has worked, but there is a problem with doubles. Also I've tried to change to doubles instead of integers in the code but it gives me an error.


#include <iostream>
#include <istream>
#include <string>
#include <fstream>
#include <stdlib.h>

using namespace std;

int main()
{
ifstream inStream;
char filename[99];
cout << "What is the name of the file? ";
cin >> filename;
inStream.open(filename);
if (inStream.fail())
{
cout << "File does not exist or is not in same folder as program" << endl;
exit(0);
}
int n;
cout << "How many numbers are there in the file? " << endl;
cin >> n;
cout << "\n";
int num[n];
int i;
for (i=0;i<n;i++)
{
inStream >> num[i];
cout << num[i] << endl;
}
return 0;
}
When posting your code, please use the code tags.

See http://www.cplusplus.com/forum/articles/16853/

I haven't taken an in depth look into the code, but glancing at it, are you sure the file name is right? According to your code, your program will attempt to open the file and read from it regardless whether the file fails to open or not.

Try this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <istream>
#include <string>
#include <fstream>
#include <stdlib.h>

using namespace std;

int main()
{
    ifstream inStream;
    char filename[99];
    cout << "What is the name of the file? ";
    cin >> filename;
    inStream.open(filename);
    if (inStream.fail())
    {
        cout << "File does not exist or is not in same folder as program" << endl;
        exit(0);
    }
    else
    {
        double n;
        while(inStream >> n)
        {
            cout << n << endl;
        }
    }
    return 0;
}
Last edited on
"It doesn't work" is not a very helpful statement, is it? Think about it! Similarly with "It gives an error". What error?!! Please use code tags; then we can refer to line numbers.

You can't read a double into an int (currently your array num[]).

In standard C++ you can't declare a standard array size at run time (although some compilers allow it).

Please be more explicit about what is wrong. Does it compile? Does it give the wrong answer? Does it crash?
Topic archived. No new replies allowed.