In: Computer Science
HW_6a - Read a text file
save it as: data.txt
in a C++ project
in the Resource folder.
4
5 Note: After you enter the 5, don’t press the enter key.
(See OUTPUT below)
/* OUTPUT
Here are the numbers in the file:
3
4
5
Press any key to continue . . . */
Please make this code based on C++, and write a description for each code.
Numbers.cpp
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("data.txt");
int a, b, c;
if (myfile.is_open())
{
cout << "Enter the three numbers: \n";
cin >> a;
cin >> b;
cin >> c;
myfile << a << endl;
myfile << b << endl;
myfile << c << endl;
myfile.close();
}
else cout << "Error opening file!";
return 0;
}
Output:
Source.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("data.txt");
if (myfile.is_open())
{
// OUTPUT
cout << "Here are the numbers in file: \n";
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Error opening file!";
return 0;
}
Output:
Thumbs Up Please !!!