我找到了一個解決方案,但我相信有更好的方法來做到這一點。如何在不使用復雜工具的情況下改進我的代碼?
string Read(string& file) {
ifstream in;
string text;
string s;
in.open(file, ios::in);
try {
while (!in.eof()) {
text.append(s);
in >> s;
}
}
catch (exception& ex) {
cout << ex.what();
}
in.close();
return text;
}
uj5u.com熱心網友回復:
您的代碼讀取空格分隔的單詞,丟棄空格,并將所有單詞連接成一個沒有空格的字串。您可能希望逐字閱讀檔案內容。
std::string在沒有回圈的情況下將整個檔案讀入 a 的一種方法是使用帶有std::string兩個迭代器的建構式 - 建構式為您執行回圈。呼叫它std::istreambuf_iterator:
#include <string>
#include <fstream>
#include <iterator>
#include <stdexcept>
std::string read(std::string filename) {
std::ifstream file(filename, std::ios_base::binary | std::ios_base::in);
if(!file.is_open())
throw std::runtime_error("Failed to open " filename);
using Iterator = std::istreambuf_iterator<char>;
std::string content(Iterator{file}, Iterator{});
if(!file)
throw std::runtime_error("Failed to read " filename);
return content;
}
uj5u.com熱心網友回復:
回圈
while (!in.eof()) {
text.append(s);
in >> s;
}
是錯誤的,因為條件while (!in.eof())可能false甚至在前一個陳述句in >> s成功的情況下。最好寫while (!in.fail())而不是while (!in.eof()).
但是,像這樣撰寫回圈會更清晰,效率更高:
while ( in >> s ) {
text.append(s);
}
此回圈條件間接使用in.operator bool(),相當于!in.fail().
這個回圈比另一個回圈更高效的原因是在另一個回圈的第一次迭代中,總是附加一個空字串。在此回圈中不再是這種情況。
uj5u.com熱心網友回復:
最簡單的方法(通常意味著最好的方法)是一次讀取一個字符的檔案
string text;
char ch;
while (file.get(ch))
text = ch;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486132.html
