简体   繁体   English

根据用户输入 c++ 替换字符串

[英]replacing string based on user input c++

i want to receive an input from user and search a file for that input.我想接收来自用户的输入并在文件中搜索该输入。 when i found a line that includes that specific word, i want to print it and get another input to change a part of that line based on second user input with third user input.当我找到包含该特定单词的行时,我想打印它并获取另一个输入以根据第二个用户输入和第三个用户输入更改该行的一部分。 (I'm writing a hospital management app and this is a part of project that patients and edit their document). (我正在编写一个医院管理应用程序,这是患者和编辑他们的文档的项目的一部分)。 i completed 90 percent of the project but i don't know how to replace it.我完成了 90% 的项目,但我不知道如何替换它。 check out following code:查看以下代码:

#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();
    
    }

for example my file contains this line ( David, ha, 2002 ) and user wants to change 2002 to 2003例如,我的文件包含这一行( David, ha, 2002 )并且用户想要将 2002 更改为 2003

Try this尝试这个

#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;
    }  
    
    
    }

First of all the header is supposed to be <fstream> rather than <stream>首先 header 应该是<fstream>而不是<stream>

I don't have much experience in File handling either but I have read that you can't read and write simultaneoudly so I have closed before reopening the file for writing.我在文件处理方面也没有太多经验,但我读到你不能同时读写,所以在重新打开文件进行写入之前我已经关闭了。

Then, instead of updating text inside the file, your line can be updated and then written to file.然后,可以更新您的line ,然后将其写入文件,而不是更新文件中的文本。

One possible way: Close the file after you read it into "line" variable, then:一种可能的方法:将文件读入“line”变量后关闭文件,然后:

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

Then overwrite the old file.然后覆盖旧文件。 Note that std::replace is different from string::replace!!请注意,std::replace 与 string::replace 不同!

You cannot replace the string directly in the file .您不能直接替换文件中的字符串。 You have to:你必须:

  1. Write to a temporary file what you read & changed.将您阅读和更改的内容写入临时文件。
  2. Rename the original one (or delete it if you are sure everything went fine).重命名原始名称(如果您确定一切正常,则将其删除)。
  3. Rename the temporary file to the original one.将临时文件重命名为原始文件。

Ideally, the rename part should be done in one step .理想情况下,重命名部分应该一步完成。 For instance, you do not want to end up with no file because the original file was deleted but the temporary one was not renamed due to some error - see your OS documentation for this.例如,您不希望最终没有文件,因为原始文件已被删除,但临时文件由于某些错误未重命名 - 请参阅您的操作系统文档。

Here's an idea:这是一个想法:

#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; found_idx = s.find(old_str, off), off += new_str.length())
    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);
  }

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM