[英]Read contents of a text file character by character into a vector without skipping whitespace or new lines
所以我有幾個文本文件。 我需要找出文件中最常見的10個字符和單詞。 我決定使用向量,並將其與文件中的每個字符一起加載。 但是,它需要包含空格和換行符。
這是我目前的功能
void readText(ifstream& in1, vector<char> & list, int & spaces, int & words)
{
//Fills the list vector with each individual character from the text ifle
in1.open("test1");
in1.seekg(0, ios::beg);
std::streampos fileSize = in1.tellg();
list.resize(fileSize);
string temp;
char ch;
while (in1.get(ch))
{
//calculates words
switch(ch)
{
case ' ':
spaces++;
words++;
break;
default:
break;
}
list.push_back(ch);
}
in1.close();
}
但是由於某種原因,它似乎不能正確容納所有字符。 我在程序的其他地方有另一個向量,該向量的256個int都設置為0。它通過向量中帶有文本的向量,並在另一個向量中以0-256 int值對字符進行計數。 但是,將它們匯總起來很好,但是空格和換行符會引起問題。 有更有效的方法嗎?
現在您的代碼存在的問題是您正在調用
list.resize(fileSize);
和使用
list.push_back(ch);
在您的讀取循環中同時進行。 您只需要一個。
忽略其中之一。
有更有效的方法嗎?
最簡單的方法是使用您已知的大小調整std::vector <char>
的大小,並使用std::ifstream::read()
一次性讀取整個文件。 之后,從矢量內容計算其他所有內容。
遵循以下原則:
list.resize(fileSize);
in1.read(&list[0],fileSize);
for(auto ch : list) {
switch(ch) {
// Process the characters ...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.