Develop a C++ program that reads a text file line by line and counts the number of…
- User
Develop a C++ program that reads a text file line by line and counts the number of occurrences of a specific word in the file.
- Assistant
Here is a simple C++ program that reads a text file line by line and counts the number of occurrences of a specific word in the file:
#include <iostream> #include <fstream> #include <string> #include <cstring> using namespace std; int main() { ifstream file("textfile.txt", ifstream::in); ofstream result("result.txt", ofstream::out); string line; int count = 0; while (getline(file, line)) { for (int i = 0; i < line.length(); i++) { if (line[i] == "word") { count++; } } result << line << endl; } result.close(); cout << "Word 'word' was found " << count << " times in the file." << endl; return 0; }This program uses the
ifstreamandofstreamclasses to open the input file "textfile.txt" and the output file "result.txt". It also uses a string variablelineto hold each line of the input file. The variablecountis used to keep track of the number of occurrences of the word "word" in each line. The program uses nested loops to iterate through each character in each line of the input file, and increments the value ofcountif it finds the character "word". The final result is written to the output file, and the number of occurrences is printed to the console.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.