Hello, I made a program that finds all the words in my .txt file and shows them to the screen, but now I want to make it so that I can pick a word from the .txt file and replace it with something else. For example :
teksts.txt has the words "dog, cat, bird" in it,
I want to choose the word "cat" and replace it with the word "rat".
Is there a simple way I can do it with useing this code as the base?
Im new to this, been looking all day, but couldnt figure it out.

I really need the help :(
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string line = " ";
    ifstream fails;

    fails.open("teksts.txt");
    while (getline (fails, line) )
        {
         cout << line << '\n';
        }

    fails.close();
    std::cin.get();
    return 0;
}

Read every word from the file, and write it out to a new file. When the word you read in is the one you want to replace, don't write the original word; write your replacement word.

When done, delete the original file and rename the the new file to match the name of the old file.

What do I have to use to select that one word I want to replace?

You can compare two string objects with ==

So Im trying out the string::find option, right now Im having a really hard time understanding it all togeather, how to make it all work togeather :(
My code is a mess I know, butIm really despret to find the answer or how/what I have to do to fix this and make it work.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string line = " ";
    ifstream fails;
    string text;
    string  text2;

    std::string str (text);
    std::string str2 (text2);

    fails.open("teksts.txt");
    while (getline (fails, line) )
        {
         cout << line << '\n';
        }

    cout << "Ievadiet vaardu kuru gribat atlasiit no faila: ";
    cin >> text;

    std::size_t found = str.find(text);

    found=str.find(text,found+1,6);

        if (found!=std::string::npos)
        std::cout << "Vaards tika atrasts: " <<text << '\n';


        cout << "Replace with the word: ";
        cin >> text2;

            str.replace(str.find(text),text.length(), text2);
          std::cout <<  text2 << '\n';


    fails.close();
    std::cin.get();
    return 0;
}

It looks like you are always replacing text in the string, whether you find something in it or not. Did you meant to do that, or is your if block crying out for a { and a } ?

Your indentation is odd and not helpful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.