如何在任何位置阅读和替换C++单词

How to read and replace a word in C++ at any location?

本文关键字:替换 C++ 单词 任何 位置      更新时间:2023-10-16

我修改文件,方法是将文件内容保存在变量/对象上,然后覆盖选定的变量/对象。然后我截断文件并使用变量/对象重写文件。无论如何,我可以仅使用简单的功能替换文件中的单词吗?

#include <iostream>
#include <conio.h>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include<cstdlib>
using namespace std;

class record{
private:
date idate;
int id;
string description;
double quantity;
double wholesalecost;
double retailcost;
public:
void createfile(){
ofstream out("abc.txt");
      }
void savedata(){
ofstream write;
write.open("abc.txt",ios::app);
write<< id<<endl;
write<< description<<endl;
write<< quantity<<endl;
write<< wholesalecost<<endl;
write<< retailcost<<endl;
write.close();
}
void readdata(int i){
    ifstream in("abc.txt");
    if(!in){
        cout<<"File opening error";
        exit(1);
    }
for(int j=0;j<i;j++){
    in>>id;
    in>>description;
    in>>quantity;
    in>>wholesalecost;
    in>>retailcost;
}
in.close();

    }
void getrecord(int recordeditems){

    id=recordeditems;
    cout<<"Enter Description of Item :";
    cin>>description;
    cout<<"Enter quantity :";
    cin>>quantity;
    cout<<"Enter Wholesale cost :";
    cin>>wholesalecost;
    cout<<"Enter Retail Cost :";
    cin>>retailcost;
}
void showrecord(){
 cout<<"* Item ID Number :"<<id<<endl;
 cout<<"* Description of Item :"<<description<<endl;
 cout<<"* Quantity of Item :"<<quantity<<endl;
 cout<<"* Wholesale cost of Item :"<<wholesalecost<<endl;
 cout<<"* Retail Cost of Item :"<<retailcost<<endl;
   }
void cleardata(){
ofstream ofs;
ofs.open("abc.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();
}
};
int main()
{
record records[50];
int recordeditems; 
ifstream in("index.txt");
in>> recordeditems;    
if(!in){               
    ofstream out("index.txt");  //create output file object
    recordeditems=0;    //set default index number =zero
    out<<recordeditems;  //write index number into the file
    }
char ch;
do{
    system("cls");
    char choice;  //character which use user choice
    cout<<"Press 'A' to Add  New Records to File"<<endl;;
    cout<<"Press 'D' to Display Any Record to File"<<endl;
    cout<<"Press 'M' to Modify any existed Record to File"<<endl;
    cout<<"Enter Choice :";
    cin>>choice;
    cin.ignore(); //"ignores next line in input"
if(choice=='A'||choice=='a'){ //if choice =A or a
         recordeditems++;  //when new record comes it increment it self
        ofstream out("index.txt"); //it recreate its file with same name
        out<< recordeditems; //it then save its value in the file
    if(recordeditems==1){ //condition when no records are saved
            records[recordeditems-1].getrecord(recordeditems);                        
            records[recordeditems-1].createfile(); 
            records[recordeditems-1].savedata();   
        }
    else{
         records[recordeditems-1].getrecord(recordeditems); 
         records[recordeditems-1].savedata();   
        }
}
else if(choice=='D'||choice=='d'){
         record call; // a temporary object to read data from file
         a: //label
         system("cls"); //clear screen command use <cstdlib> library
         int i;
         cout<<"Which Recorded Item, Would you like to display :";
         cin>>i;
         if(i>recordeditems){
            cout<<"Record item is not stored yet"<<endl;
            system("pause");
            goto a;
         }
         call.readdata(i); //that temporary object reads data from file
         call.showrecord();// then display it
}
else if(choice=='M'||choice=='m'){
         int mod;
        for(int i=0;i<recordeditems;i++){
            records[i].readdata(i+1);    
        }
         cout<<"Enter which record number you want to modify :";
          cin>>mod; //which object number you want to modify ?
          cin.ignore(); //ignores the next line
          records[mod-1].getrecord(mod); 
          records[mod-1].cleardata(); 

        for(int j=0;j<recordeditems;j++){
                records[j].savedata();  
             }
 }
else{
    cout<<"Invalid Choice ";
    }
cout<<endl<<"Enter 'y' to go back to menu or press any other key to quit";
ch=_getch(); //input character with out press enter on it
}while(ch=='y'||ch=='Y');
return 0;
}

如果您想搜索文件并替换特定单词,整个事情很容易......您所要做的就是编写一个小搜索引擎,它将遍历整个文件,然后返回单词的位置。然后,您需要做的就是跳转到该位置,然后删除单词并添加所需的任何内容。

这是一个函数的小示例,该函数搜索字符串数组data中是否存在搜索的单词。 Lines代表文件的行

bool inIt(std::string Input, std::string find){
    int total = Input.length();
    int findl = find.length();
    if (total < findl){ return false; }//if our base string is shorter, they can't be equal
    for (int offset = 0; offset <= total - findl; offset++){//the string with an offset mustn't be longer than the base
        std::stringstream addchar;
        for (int read = offset; read < findl + offset; read++){//read the length of the compare string
            addchar << Input[read];//read the string with an offset
        }
        //compare
        if (addchar.str() == find){
            return true;//if our new string is the same as our compare string we end searching
        }
    }
    return false;//nothing found
}

为了找到字符串所在的行,请使用以下命令:

int findAt(std::string what, int fromLine=1){
    if (fromLine >= Lines){ return -1; }
    //std::cout << "searching... ";
    for (int n = fromLine; n < Lines+1; n++){
        //std::cout << std::endl << data[n] << " = ";
        bool ret = inIt(data[n], what);
        if (ret){ 
            //std::cout << "FOUND at " << n << std::endl;
            return n;
        }
    }
    //std::cout << "not found!" << std::endl;;
    return -1;
}

我认为你可以编写最后一个函数,它会自己找到并替换行中的单词。顺便说一句,这是我的一个项目的片段,所以如果我不清楚,请问我。

可能有一些拼写错误,很抱歉,但我不是本地人