【问题标题】:replacing string based on user input c++根据用户输入替换字符串c ++
【发布时间】:2022-01-21 21:07:43
【问题描述】:

我想接收来自用户的输入并在文件中搜索该输入。当我找到包含该特定单词的行时,我想打印它并获取另一个输入以根据第二个用户输入和第三个用户输入更改该行的一部分。 (我正在编写一个医院管理应用程序,这是患者和编辑他们的文档的项目的一部分)。 我完成了 90% 的项目,但我不知道如何替换它。查看以下代码:

#include <iostream>
#include <stream>
#include <string.h>
#include <string>
using namespace std; 

int main(){
    string srch;
    string line;
    fstream Myfile;
    string word, replacement, name;
    int counter;
    Myfile.open("Patientlist.txt", ios::in|ios::out);
    cout << "\nEnter your Name: ";
    cin.ignore();
    getline(cin, srch);

    if(Myfile.is_open())
    {
        while(getline(Myfile, line)){
            if (line.find(srch) != string::npos){
                cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
                cin >> word >> replacement;
            } 
            // i want to change in here
        }
    }else
    {
        cout << "\nSearch Failed...  Patient not found!" << endl;
    }  
    Myfile.close();
    
    }

例如我的文件包含这一行 (David , ha , 2002 ) 并且用户想要将 2002 更改为 2003

【问题讨论】:

  • 不能直接替换文件中的字符串。您必须在第二个文件中写入您读取的内容,然后重命名/删除原始文件,然后将输出文件重命名为原始名称。
  • @zdf 你能用代码告诉我我该怎么做吗?我没有太多使用 C++ 的经验,非常感谢

标签: c++ string file replace


【解决方案1】:
  • 标题应该是&lt;fstream&gt; 而不是&lt;stream&gt;

  • 您不能同时读取和写入文件,因此我在读取后关闭文件,然后重新打开文件进行写入。

  • 您的line 可以更新然后写入文件,而不是更新文件中的文本。

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

int main(){
    string srch;
    string line, line2;
    fstream Myfile;
    string word, replacement, name;
    int counter;
    Myfile.open("Patientlist.txt", ios::in);
    cout << "\nEnter your Name: ";
    cin.ignore();
    getline(cin, srch);

    if(Myfile.is_open())
    {
        while(getline(Myfile, line)){
            if (line.find(srch) != string::npos){
                cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
                cin >> word >> replacement;

                int index = line.find(word);

                if (index != string::npos){
                    Myfile.close();

                    Myfile.open("Patientlist.txt", ios::out);

                    line.replace(index, word.length(), replacement);
                    Myfile.write(line.data(), line.size());

                    Myfile.close();
                }
            } 
            // i want to change in here
        }
    }else
    {
        cout << "\nSearch Failed...  Patient not found!" << endl;
    }  
    
    
    }

【讨论】:

    【解决方案2】:

    您不能直接在文件中替换字符串。你必须:

    1. 将您阅读和更改的内容写入临时文件
    2. 重命名原件(如果您确定一切正常,则将其删除)。
    3. 将临时文件重命名为原始文件。

    理想情况下,重命名部分应该一步完成。例如,您不希望最终没有文件,因为原始文件已被删除,但临时文件由于某些错误未重命名 - 请参阅您的操作系统文档。

    这是一个想法:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <cstdio>
    
    using namespace std;
    
    void replace(string& s, const string& old_str, const string& new_str)
    {
      for (size_t off = 0, found_idx = s.find(old_str, off); found_idx != string::npos; off += new_str.length(), found_idx = s.find(old_str, off))
        s.replace(found_idx, old_str.length(), new_str);
    }
    
    int main()
    {
      const char* in_fn = "c:/temp/in.txt";
      const char* bak_fn = "c:/temp/in.bak";
      const char* tmp_fn = "c:/temp/tmp.txt";
      const char* out_fn = "c:/temp/out.txt";
    
      string old_str{ "2002" };
      string new_str{ "2003" };
    
      // read, rename, write
      {
        ifstream in{ in_fn };
        if (!in)
          return -1; // could not open
    
        ofstream tmp{ tmp_fn };
        if (!tmp)
          return -2; // could not open
    
        string line;
        while (getline(in, line))
        {
          replace(line, old_str, new_str);
          tmp << line << endl;
        }
      } // in & tmp are closed here
    
      // this should be done in one step 
      {
        remove(bak_fn);
        rename(in_fn, bak_fn);
    
        remove(out_fn);
        rename(tmp_fn, in_fn);
    
        remove(tmp_fn);
      }
    
      return 0;
    }
    

    【讨论】:

      【解决方案3】:

      一种可能的方式: 将文件读入“line”变量后关闭文件,然后:

      std::replace(0, line.length(), "2002", "2003")

      然后覆盖旧文件。 注意 std::replace 与 string::replace 不同!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        • 2021-09-06
        • 2019-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多