优化前的代码:
#include <fstream>
#include <iostream>
#include <string>
int main()
{
using namespace std;
// ifstream is used for reading files
// We'll read from a file called Sample.txt
//char str[256];
//cout << "Enter the name of an existing wokflowlog file: " << endl;
//cin.get (str,256);
//ifstream inf.open(str);
ifstream inf("Sample.txt");
// If we couldn't open the output file stream for reading
if (!inf)
{
// Print an error and exit
cerr << "Uh oh, Sample.txt could not be opened for reading!" << endl;
exit(1);
}
// While there's still stuff left to read
while (inf)
{
// read stuff from the file into a string and print it
string strInput;
inf >> strInput;
cout << strInput << endl;
}
return 0;
// When inf goes out of scope, the ifstream
// destructor will close the file
}
输出结果如下图:
优化后的代码:
#include <fstream>
#include <iostream>
#include <string>
int main()
{
using namespace std;
// ifstream is used for reading files
// We'll read from a file called Sample.txt
ifstream inf("Sample.txt");
// If we couldn't open the input file stream for reading
if (!inf)
{
// Print an error and exit
cerr << "Uh oh, Sample.txt could not be opened for reading!" << endl;
exit(1);
}
// While there's still stuff left to read
while (inf)
{
// read stuff from the file into a string and print it
std::string strInput;
getline(inf, strInput);
cout << strInput << endl;
}
return 0;
// When inf goes out of scope, the ifstream
// destructor will close the file
}
输出结果如下图: