I wrote a selling ticket program for a concern into a text file name "Sales.txt" to show the TotalValue with the following format:

21
30
40
24
87
44
51
29
58
20

Totally, I have 10 values.
However, my new assignment asks me to make a new program that read the values that I caputed in the text file into an array.
This is my new program:

Bold Text Here #include <iostream>

include <string>
include <fstream>

using namespace std;

int main()
{
ifstream inputFile;
string filename;
int number;

cout << "Enter file name: ";
cin >> filename;

inputFile.open(filename.c_str());


if (inputFile)
{
    while (inputFile >> number)
    {
        cout << number << endl;
    }

    inputFile.close();
}
else {
    cout << "Error";
}
return 0;

}

I dont know where I am wrong, but I can't open my file when I run and type Sales.txt. It keeps saying error or shows only the first value.

please help me with this.

The only thing I see wrong is absence of the # sign before the 2 of the three includes.

Instead of if (inputFile), try if (inputFile.is_open()).

And when posting your code, please select all of it and click the Code button at the top of the editor, or just hit the tab-key to do the same thing. Then all of your code will get line-numbered and formatted together, instead of starting at the first indent.

move the inputFile.close(); out of the if statement and put it between the bracket and return 0; (line 18 and line 19)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.