【问题标题】:How to read and replace a word in C++ at any location?如何在任何位置读取和替换 C++ 中的单词?
【发布时间】:2016-05-22 10:23:04
【问题描述】:

我通过将文件内容保存在变量/对象上来修改文件,然后覆盖选定的变量/对象。然后我截断文件并用变量/对象重写文件。无论如何,我可以通过使用简单的函数来替换文件中的一个单词吗?

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

【问题讨论】:

  • 没有。到目前为止,您尝试过什么?
  • 请给我们看一个简约的例子,展示你到目前为止所做的尝试。

标签: c++ file-handling


【解决方案1】:

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

这是一个函数的小例子,它搜索搜索的单词是否存在于字符串数组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;
}

我认为你可以编写最后一个函数,它会自行查找和替换行中的单词。 顺便说一句,这是我的一个项目的 sn-ps,所以如果我留下不清楚的地方,问我。

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

【讨论】:

  • 那么您可能想要接受该答案并/或投票:)
猜你喜欢
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
相关资源
最近更新 更多