Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Enter from keyboard a letter. Read text from given text file and print into another text file all words starting with entered letter and row number where word was found in given file. 


What I have tried:

#include <bits/stdc++.h>
using namespace std;

// driver code
int main()
{
    fstream file;

    // Input stream class to
    // operate on files.
    ifstream ifile("file.txt", ios::in);

    // Output stream class to
    // operate on files.
    ofstream ofile("file2.txt", ios::out | ios::app);

    // check if file exists
    if (!ifile.is_open()) {

        // file not found (i.e, not opened).
        // Print an error message.
        cout << "file not found";
    }
    else {
        // then add more lines to
        // the file if need be
        ofile << ifile.rdbuf();
    }
    string word;

    // opening file
    file.open("file2.txt");

    // extracting words form the file
    while (file >> word) {

        // displaying content of
        // destination file
        cout << word << " ";
    }

    return 0;
}
Posted
Updated 22-Jan-22 14:34pm
Comments
merano99 22-Jan-22 19:51pm    
What is your Question?
The task would be to read the text row by row, since the row number should be output.

1 solution

Looks like a good start. Before you enter the while loop, you need to read a character from the keyboard (cin). And each time you read a word in the while loop, you need to increment a line number, check if the word that you read begins with the specified character and, if so, write the line number and word to the output file.
 
Share this answer
 
Comments
Peter_in_2780 22-Jan-22 21:14pm    
I think the "good start" is the driver scaffolding provided by the instructor....
Greg Utas 23-Jan-22 8:08am    
Yes, I thought that was certainly possible.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900