我撰寫了一個程式來計算外部檔案中的單詞和元音。我能夠通過撰寫兩個 while 回圈來實作這一點。但是,如果我注釋掉其中一個 while 回圈,它只能產生所需的結果,這意味著它只會輸出一個回圈的正確結果。我不知道如何解決這個特殊情況。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int words = 0, vowels = 0;
string word;
char letter;
ifstream inFile;
int main() {
//open file
inFile.open("lorem.txt");
//process file
while (inFile >> word) {
words ;
}
while(inFile.get(letter)){
if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i'|| letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U'){
vowels ;
}
}
cout << "The input file contains "<< words << " words and " << vowels<< " vowels"<<endl;
return 0;
}
uj5u.com熱心網友回復:
在任一 while 回圈結束時,inFile已到達檔案末尾。
很明顯,您的兩個while回圈都希望從檔案的開頭開始讀取。
將此行放在兩個 while 回圈之間,以再次從檔案開頭開始讀取。
inFile.seekg(0); // Return to byte 0 of the file
uj5u.com熱心網友回復:
我不建議重置檔案指標。因為您隨后會讀取該檔案 2 次。
這是沒有必要的。如果讀過這個詞,那么你也可以檢查這個詞是否有元音。這可以通過迭代單詞的字母來簡單地完成。
因此,首選解決方案如下所示:
#include <iostream>
#include <fstream>
int main() {
std::ifstream inFile("lorem.txt");
int words = 0;
int vowels = 0;
std::string word;
while(inFile >> word) {
words ;
for (char letter : word)
if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i'|| letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U'){
vowels ;
}
}
std::cout << "The input file contains "<< words << " words and " << vowels<< " vowels\n";
}
而且,如果您想使用更現代的 C 解決方案,可能還有數百萬個解決方案。一張在下面:
#include <iostream>
#include <fstream>
#include <sstream>
#include <regex>
#include <iterator>
struct in {
in(const std::initializer_list<char>& il) : ref(il) {}
const std::initializer_list<char>& ref;
};
bool operator,(const char& lhs, const in& rhs) {
return std::find(rhs.ref.begin(), rhs.ref.end(), lhs) != rhs.ref.end();
}
const std::regex re{R"(\w )"};
int main() {
// Open a file and check, if it could be opened
if (std::ifstream inFile("lorem.txt"); inFile) {
// Read the complete file into a string
std::string text(std::istreambuf_iterator<char>(inFile),{});
// Count all words
size_t wordsCount = std::distance(std::sregex_token_iterator(text.begin(), text.end(), re), {});
size_t vowelsCount{};
// Go over all characters in the file (in a string)
for (char c : text)
// If the character is a vowel
if (c, in{'a','e','i','o','u','A','E','I','O','U'})
vowelsCount;
// Show result
std::cout << "The input file contains "<< wordsCount << " words and " << vowelsCount<< " vowels\n";
}
else std::cerr << "\nError: Could not open inpute file\n\n";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/319242.html
