Question: C++ 1. Open a project , and a . cpp file. 2. Choose File, New from the menu and choose Text File . Once the

C++

1. Open a project, and a .cpp file.

2. Choose File, New from the menu and choose Text File. Once the text file is opened, go to the File menu again and choose the option that says move into the project. Your text file should show in the Solution Explorer Window.

3. Copy the following into your text file.

5

6

-9

22

3

4. Copy the following code into your source code.

#include

//header file needed for files

#include

using namespace std;

int main()

{

//program to add numbers from a file

//declarations for file stream variables

ifstream inFile;

ofstream outFile;

//declarations for other variables

int total = 0;

int inputVal;

inFile.open("data.txt"); //put the name of your text file in the quotes

outFile.open("out.txt"); //this file will be created when the program runs

//read from the file

inFile >> inputVal;

//do the loop while there are still numbers in the file

while (!inFile.eof())

{

total += inputVal;

inFile >> inputVal;

}

//output to the standard output and to a file

cout << "The total is: "<< total << endl;

outFile << "The total is: " << total << endl;

//close files

inFile.close();

outFile.close();

return 0;

}

5. Run your code. What is the output?

6. Change your code so that it only adds the positive numbers in the file.

7. Change your code so that the main function only opens the files, calls a function that sums the numbers, and closes the file.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!