C++ 逐行讀取文字檔案
阿新 • • 發佈:2019-02-03
#include <fstream>// std::ifstream #include <iostream>// std::wcout #include <vector> #include <string> using std::vector; using std::wstring; // int read_file(vector<wstring> &data, wstring szFile) { data.clear(); // std::wifstream file_(szFile.c_str(), std::ios::in); //std::wifstream file_; //file_.open(szFile.c_str(), std::ios::in); const int bufsize = 512; wchar_t strbuf[bufsize]; // while( !file_.eof() ) { file_.getline(strbuf, bufsize); wstring sentence = strbuf; if (sentence.empty()) { continue; } data.push_back(sentence); } file_.close(); // if (data.size() < 1) { return -1; } return 0; }
測試程式碼:
int main()
{
vector<wstring> result;
if (read_file(result, L"test.txt") == 0)
{
for (int i=0; i<result.size(); ++i)
{
std::wcout << result[i] << std::endl;
}
}
system("pause");
return 0;
}