-1

I am fairly new to filing in C++ and I am trying to build a program which takes the input from the user for the text file, asks the user which word he/she wants to replace and displays the text file after replacing the word. Program shows no errors but fails to achieve the desirable output. enter image description here

#include<fstream.h>
#include<stdio.h>
#include<string.h>


void getdata(){
  char s[80];
  int n;

    cout<<"How many lines would you like to enter\n";
    cin>>n;cout<<"Please go ahead\n"<<endl;

  ofstream f1("story.txt");

    for(int i=0;i<=n;i++){
    cin.getline(s,80);
    f1<<s;
     }
        f1.close();
 }


  void showdata(fstream& f1){
 char s[80];

  f1.open("story.txt",ios::in);

    while(!f1.eof()){
     f1>>s;
     cout<<s<<" ";
     }
        f1.close();
 }



void main(){
 char s[20], replace[20];
 getdata();
  cout<<endl<<"which word do you want to replace\n";
  cin>>s;
    cout<<endl<<"what do you want to replace it with?\n";
    cin>>replace;


     fstream f1("Story.txt",ios::in);
     fstream f2("temp.txt",ios::out);

     char word[20];

      while(!f1.eof()){
        f1>>word;
         if(strcmp(word,s))
         strcpy(word,replace);
        f2<<word;
      }

         f1.close();
         f2.close();
         showdata(f2);
          remove("story.txt");
          rename("temp.txt","story.txt");


 }
Rockboy987
  • 131
  • 1
  • 6

1 Answers1

0

I can see two problems with your code (aside from the obvious problem of using Turbo C++):

  1. strcmp returns falsy value when strings are equal.

Your if condition should look like this:

     if(strcmp(word,s) == 0)
  1. You output data from different text file than you wrote to

If you'd open story.txt in your favourite text editor after execution of your program, you'd (probably) notice it looks like this:

apple banana banana banana banana banana banana 

This is due to point 1., but notice that the file actually changed. The thing is, you open story.txt for reading again before it was renamed from temp.txt, so when you output it to the screen, it still has the old content (and temp.txt has the new stuff)

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52