Я пытаюсь прочитать текстовый файл, чтобы узнать, сколько раз появляется фраза/предложение (/substring?). В настоящий момент я сделал настоящую работу над ним (см. Код ниже), но, как вы увидите, он опирается на некоторые довольно неуклюжие утверждения if.
У меня нет доступа к файлам, которые я буду использовать в домашних условиях, поэтому я использовал файл с именем big.txt и искал фразы типа "и" пока.
В идеале я бы хотел найти "этот код ошибки 1" и вернуть количество раз, когда оно происходит. Любые идеи о том, как я могу заставить мой код работать таким образом, были бы невероятно полезны!
int fileSearch(string errorNameOne, string errorNameTwo, string textFile) {
string output; //variable that will store word from text file
ifstream inFile;
inFile.open(textFile); //open the selected text file
if (!inFile.is_open()) {
cerr << "The file cannot be opened";
exit(1);
}
if (inFile.is_open()) { //Check to make sure the file has opened correctly
while (!inFile.eof()) { //While the file is NOT at the end of the file
inFile >> output; //Send the data from the file to "output" as a string
if (output == errorNameOne) { //Check to look for first word of error code
marker = 1; //If this word is present, set a marker to 1
}
else if (marker == 1) { //If the marker is set to 1,
if (output == errorNameTwo) { //and if the word matches the second error code...
count++; //increse count
}
marker = 0; //either way, set marker to 0 again
}
}
}
inFile.close(); //Close the opened file
return count; //Function returns count of error
}
Учитывая, что ваша фраза может возникать только один раз в строке, а число следует за фразой после нескольких пробелов, вы можете прочитать файл по строкам и использовать std :: string :: find(), чтобы увидеть вашу фразу где-то в строке, Это вернет позицию фразы. Затем вы можете проверить оставшуюся часть строки сразу после фразы, чтобы проверить номер на 1 или 0.
Этот код может быть не совсем то, что вы хотите (все еще не уверены в точном описании), но, надеюсь, он должен содержать достаточно примеров того, что вы можете сделать для достижения своей цели.
// pass the open file stream in to this function along with the
// phrase you are looking for and the number to check
int count(std::istream& is, const std::string& phrase, const int value)
{
int count = 0;
std::string line;
while(std::getline(is, line)) // read the stream line by line
{
// check if the phrase appears somewhere in the line (pos)
std::string::size_type pos = line.find(phrase);
if(pos != std::string::npos) // phrase found pos = position of phrase beginning
{
// turn the part of the line after the phrase into an input-stream
std::istringstream iss(line.substr(pos + phrase.size()));
// attempt to read a number and check if the number is what we want
int v;
if(iss >> v && v == value)
++count;
}
}
return count;
}
int main()
{
const std::string file = "tmp.txt";
std::ifstream ifs(file);
if(!ifs.is_open())
{
std::cerr << "ERROR: Unable to open file: " << file << '\n';
return -1;
}
std::cout << "count: " << count(ifs, "Header Tangs Present", 1) << '\n';
}
Надеюсь это поможет.