从文本文件中读内容(显示到控制台界面上)

来源:互联网 发布:动易网络注册 编辑:程序博客网 时间:2024/05/06 08:03

优化前的代码:

#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 readingif (!inf){// Print an error and exitcerr << "Uh oh, Sample.txt could not be opened for reading!" << endl;exit(1);}// While there's still stuff left to readwhile (inf){// read stuff from the file into a string and print itstring 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.txtifstream inf("Sample.txt");// If we couldn't open the input file stream for readingif (!inf){// Print an error and exitcerr << "Uh oh, Sample.txt could not be opened for reading!" << endl;exit(1);}// While there's still stuff left to readwhile (inf){// read stuff from the file into a string and print itstd::string strInput;getline(inf, strInput);cout << strInput << endl;}return 0;// When inf goes out of scope, the ifstream// destructor will close the file}
输出结果如下图: