c++ - C ++提取和计算文本文件中的单词数
问题描述
我的任务是从文本文件中读取并计算字数,同时将文本显示到控制台。每当我调用“getString”函数时,“numCount”都会变为 0。如果我将“getString”函数注释掉,numCount 会显示正确的字数。因此,这两个函数看起来就像它们都被调用时才起作用,然后我遇到了这些问题。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void getFileInfo(ifstream &inFile);
int numOfWords(ifstream& inFile); // counts number of words
string getString(ifstream &inFile); // retrieves string from textfile
int main(){
string fileName, words, str;
ifstream inFile;
int count;
getFileInfo(inFile);
str = getString(inFile);
count = numOfWords(inFile);
cout << "In the sentence, '" << str << "', there are " << count << " words " << endl;
}
void getFileInfo(ifstream &inFile){
string fileName;
do{
cout << "Please enter the filename: " << endl;
cin >> fileName;
inFile.open(fileName.c_str());
if(!inFile){
cout << "Invalid try again" << endl;
}
}while(!inFile);
}
int numOfWords(ifstream& inFile){
string fileName, words, str;
int numCount =0;
while(inFile >> words){
++numCount;
}
return numCount;
}
string getString(ifstream &inFile){
string str;
while(inFile)
getline(inFile, str);
return str;
}
解决方案
您的问题是您没有在之后重置流getString()
C++ iostreams 有一种隐喻光标,您读取的每一位都会将光标移动到下一位(因此您无需手动移动光标即可读取它)。inFile
您的代码中的问题是光标位置在after的末尾结束getString()
,这意味着循环getNumOfWords()
永远不会运行。
您需要做的是在getString()
. 例子:
std::string getString(ifstream& inFile) {
...
inFile.clear() // <-- You may need this depending on your iostream implementation to clear the EOF failbit
inFile.seekg(0, ios::beg);
return str;
}
推荐阅读
- maven - 如何使用 jacoco 对多 maven 模块强制执行单元测试覆盖
- javascript - 在数组中添加新的键和值
- flutter - 初始化和提供程序的颤振问题
- flutter - 使用正则表达式进行表单验证在颤振中不起作用
- swift - 调整大小后部分 UITextView 不起作用
- azure - 无法创建 Azure AKS 群集:CreateRoleAssignmentError
- apache-kafka - 了解 Kafka poll()、flush() 和 commit()
- javascript - 无服务器功能上的 Next.js 和 Auth0(使用 Passport.js)
- python-3.x - 我如何发现和活跃