Идея состоит в том, чтобы взять файл и распечатать количество слов в файле. Затем предложите пользователю ввести слово, программа будет подсчитывать, сколько раз это слово повторяется. Однако у меня возникли проблемы с будучи в состоянии чтобы выбрать выбранное слово из файла, независимо от того, что она по-прежнему возвращает 0.Не удалось успешно сравнить строки
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream infile;
int i = 0;
string word_counter;
string file_name;
bool opened = false;
while (opened == false){
cout << "Enter the name of the file to read: ";
cin >> file_name;
infile.open(file_name, fstream::in);
opened = true;
if (!infile.is_open()) {
cout << "ERROR: CANNOT OPEN INPUT FILE" << endl;
cout << endl;
opened = false;
}
}
while (!infile.eof()){
infile >> word_counter;
cout << word_counter << endl;
i++;
}
cout << "Read in " << i << " words\n";
bool done = false;
while (!done){
string word;
string quit;
int x = 0;
cout << "Enter a word to count how many times it occurs: ";
cin >> word;
while (!infile.eof()){
infile << word_counter;
if (word_counter == word){
x++;
}
}
cout << "The word \"" << word << "\" occurs " << x << " times" << endl;
cout << "Press any key to continue, or press Q to quit: ";
cin >> quit;
if (quit == "q" || quit == "Q"){
done = true;
}
}
infile.close();
return 0;
}
Почему бы не попробовать использовать .compare()? некоторые ссылки: http://stackoverflow.com/questions/9158894/differences-between-c-string-and-compare – Intan
Почему бы не использовать 'strcpm (word_counter, слово)' для сравнения строк. –