Number Analysis program

I'm trying to write a program that opens file , which contains a set of numbers. The program should then read the contents of the file into an array but it only opens the file and doesn't read any of the data. Is there something wrong with my code? I would really appreciate any help.

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
32
33
34
35
  #include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    ifstream datafile;
    string filename;
    const int NUM_PLACES = 10;
    double numbers[NUM_PLACES];
    int count = 0;

    datafile.open("numbers.txt");

    if (!datafile)
    {
        cout << "Error opening the file.\n";
    }
    else
    {
        while ( count < NUM_PLACES && datafile >> numbers[count] )
            count++;

        datafile.close();

        cout << "The numbers are\n";
        for (int place = 0; place < count; place++)
        {   cout << numbers[place] << endl;

        }
    }
    return 0;
}
Last edited on
Using your code with a text file containing 1.2 3.4 5.6 7.8 9.0 worked fine.How does your text file look like?
this is my text file
106
102
109
104
105
106
107
108
109
103
I changed it a little but now I get a different error

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
ifstream inputFile;
string filename;
const int NUM_PLACES = 10;
double numbers[NUM_PLACES];
int count = 0;

cout << "Enter the filename: ";
cin >> filename;

inputFile.open(filename.c_str());

if (inputFile)
{
while ( count < NUM_PLACES && inputFile >> numbers[count] )
cout << "The numbers are\n";
for (int place = 0; place < count; place++)
{ cout << numbers[place] << endl;

}
inputFile.close();
}
else
{
cout << "Error opening the file.\n";
}
return 0;
}

i get
LINK||fatal error LNK1181: cannot open input file 'obj\Debug\numbers.obj'|

works for me with your text file as well.Are you sure it finds the file?
There is nothing wrong with your code. the first one.
Just make sure the text file you want your program to read from is named "numbers" and saved in the same directory/location as your cpp source code

i.e

if your source code is located at c:\users\username\documents\mycode
the text file should also be saved at c:\users\username\documents\mycode
Last edited on
Topic archived. No new replies allowed.