簡體   English   中英

在函數中使用文本文件替換單詞時獲得不想要的輸出

[英]Getting undesirable output while using text file in function to replace a word

我對用 C++ 歸檔還很陌生,我正在嘗試構建一個程序,該程序從用戶那里獲取文本文件的輸入,詢問用戶他/她想要替換哪個單詞,並在替換單詞后顯示文本文件。 程序未顯示任何錯誤,但未能實現所需的輸出。 在此處輸入圖片說明

#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");


 }

我可以看到您的代碼存在兩個問題(除了使用 Turbo C++ 的明顯問題):

  1. 當字符串相等時, strcmp返回值。

您的if條件應如下所示:

     if(strcmp(word,s) == 0)
  1. 您從與寫入的文本文件不同的文本文件中輸出數據

如果您在執行程序后在您喜歡的文本編輯器中打開story.txt ,您(可能)會注意到它看起來像這樣:

apple banana banana banana banana banana banana 

這是由於第 1 點。但請注意,文件實際上已更改 問題是,temp.txt重命名之前,您再次打開story.txt進行閱讀,因此當您將其輸出到屏幕時,它仍然具有舊內容(並且temp.txt具有新內容)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM