gpt4 book ai didi

c++ - 如何从文本文件中的字符串中提取特定单词? C++

转载 作者:行者123 更新时间:2023-12-02 10:19:58 25 4
gpt4 key购买 nike

我的任务是从文本文件中提取一个字符串并计算其中的单词数。我已经走了那么远,但是现在我们必须能够取一个特定的数字并将该数字单词显示在控制台上。假设我输入的字符串是“Hello World”,如果我输入“2”,则结果应该为“World”。我不确定我的函数应该如何查找。到目前为止,这是我的代码。

void getFileInfo(ifstream &inFile);
string words(ifstream &inFile);
int numOfWords(ifstream& inFile);


int main() {

ifstream inFile;
string sentence, fileName;
int numCount, word;

getFileInfo(inFile);
numCount = numOfWords(inFile);
inFile.clear(); // resets file pointer from the beginning
inFile.seekg( 0 );
sentence = words(inFile);

cout << sentence << ": has " << numCount << " words in it" << endl;
cout << "Enter a number to extract a word: ";
cin >> word;


}

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);

}

string words(ifstream &inFile){

string words, theWords;

getline(inFile, words);
cout << words;



return theWords;

}

int numOfWords(ifstream& inFile){

string fileName, words, str;
int numCount =0;

while(inFile >> words){
++numCount;
}

return numCount;


}

有什么建议么?

提前致谢

最佳答案

我会为您的任务建议稍有不同的代码。首先,编写一些简单的辅助函数:

// Clear error flags (EOF, for example) and reset stream to the beginning.
void resetStream(ifstream& stream) {
stream.clear();
stream.seekg(0, ios_base::beg);
}

// Count the words in text file stream.
int getWordsCount(ifstream& stream) {
int count = 0;

while (stream) {
string tmp;
stream >> tmp;
if (!tmp.empty()) ++count;
}

resetStream(stream);

return count;
}

// Read word by specific number.
string getWordByNumber(int number, ifstream& stream) {
string word;

while (number--)
stream >> word;

resetStream(stream);

return word;
}

现在,您可以轻松获取文件中的单词数,并通过其数量显示特定单词。例如:
int main() {
string fileName;
cout << "Enter the file name: \n";
cin >> fileName;

ifstream stream(fileName);

if (!stream)
cout << "Failed to open file!" << endl;
else {
int totalCount = getWordsCount(stream);
int currentCount = 0;

cout << "Total words count: " << totalCount << "\n\n";

do {
cout << "Enter the word number (enter '0' to finish): ";
cin >> currentCount;

if (currentCount == 0) break;
else if (currentCount > totalCount)
cout << "Invalid value!\n";
else {
string wordByNumber = getWordByNumber(currentCount, stream);
cout << "Word by number: " << "'" << wordByNumber << "'\n";
}

cout << "\n";
}
while (true);
}

return 0;
}

警告:该代码不是很有效,我还没有对其进行太多测试。如果您有任何问题,请务必发表评论。

关于c++ - 如何从文本文件中的字符串中提取特定单词? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60662791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com