首页 > 解决方案 > 如何在 C++ 中打印相关行?

问题描述

在我的代码中,我想要一个名为search的函数,它遍历 .txt 文件中的每一行,如果句子中的第一个数字包含用户给出的数字,则打印出该行。例如:

.txt 文件的格式:

每个单词都用空格隔开。

17 35 "door"
40 19 "wall"
17 34 "car"
3  9  "window"

输出:

Enter a desired number:17
17 35 "door"
17 34 "car"

我该怎么做呢?在java中,我通常会使用 .split() 函数将句子拆分成一个列表,然后查看第一个索引是否与所需的输入匹配,但我找不到如何做到这一点,我能找到什么,我不知道不明白。下面列出了我的尝试,但是如果您有更好的方法,请列出它们...我还在学习中。我的尝试位于下面的搜索功能下:

#include<iostream> 
using std::cerr;
using std::endl;
#include <list>
using namespace std; 
#include <fstream>
using std::ofstream;
#include <cstdlib> // for exit function
#include <sstream>
using namespace std;

class Item{

//Access specifer
public: //todo, private with get/set 
string item;
int meshNum;
int mNum;

//constructor 
public:
Item( string item,int mNum, int meshNum  ){
    this->item=item;
    this-> mNum= mNum;
    this-> meshNum= meshNum;
    
}

//Memeber functions
public: 
string getItem(){
    return item;
}
void setItem(string item){
    this->item = item;
}
int getMeshNum(){
    return this->meshNum;
}
void setMeshNum(int meshNum){
    this->meshNum= meshNum;
}

int getMNum(){
    return this->mNum;
}
void setMNum(int mNum){
    this-> mNum= mNum;
}

};
//____________________________________________

 class materialList{
// Access specifer
private: 
list <Item> items;
 
 //constructor 
 public:
/* materialList(){
     this->items = new list<Item>;
} */

 // Memeber fucntions
 public:
 void add(Item &item)
 {
     items.push_back(item);
 }
//print my list
void Print()
 {
     ofstream outdata; // outdata is like cin
     outdata.open("example2.dat"); // opens the file
   if( !outdata ) { // file couldn't be opened
      cerr << "Error: file could not be opened" << endl;
      exit(1);
   }

    for (auto &i : items)
         outdata  << i.getItem() << " "<<i.getMeshNum()<< " "<<i.getMNum()<<endl;  
      
    outdata.close();
 
   
}
void search(ifstream& inFile){ //this function is where I need help on =<
    string line,word;
    int materialNum;
    istringstream iss;
    cout<< "Enter a material number:";
    cin>>materialNum;
    int**arr= (int**)malloc(20*sizeof(int*));
    int i=0;

    while(!inFile.eof()){
        // read line by line from the file
        getline(inFile,line); 
        if(inFile.good()){
            // read word by word in line and place words in arr
            iss.clear(); // clear out state
            iss.str(line);
            iss>> word;
            arr[i]=word;
            
         }
            if (word==cin){
             cout>>line; 
          }
         
        }
    }
    
};
    






 int main(){
     bool value = true;
     string objectName;
     int Mnum;
     int Meshnum;
     materialList ml; //(list<Item> test);
     while(value){
         cout<< "Enter Object name: ";
         cin>> objectName;
         cout<<" Enter M#: ";
         cin>> Mnum;
         cout<<"Enter Mesh#: ";
         cin>> Meshnum;
         //Item second= Item(objectName,Mnum,Meshnum);
         ml.add(Item(objectName,Mnum,Meshnum));
         ml.Print();

     }
     
     
     //Item test= Item("door",34,50);
     //itemList = 
     
     //ml.add(test);
     //ml.Print();

 }

错误:

material_characterizationf.cpp:105:20: error: assigning to 'int *' from incompatible type 'std::__1::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
            arr[i]=word;
                   ^~~~
material_characterizationf.cpp:134:17: error: non-const lvalue reference to type 'Item' cannot bind to a temporary of type 'Item'
         ml.add(Item(objectName,Mnum,Meshnum));
                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我知道第一个错误来自我失败的尝试,但我不知道第二个错误来自哪里。在我尝试添加搜索功能之前,代码运行良好。

标签: c++

解决方案


在您的search函数中,我认为您不需要使用arr数组,因为它不仅会导致内存泄漏,因为它在函数结束时没有被释放,而且它在函数中没有任何用途。您可以通过intword变量设置wordinttype 而不是string.

这样,您可以word检查它是否等于materialNum(不等于cin在您的原始代码中,因为它是一个istream对象并且不能与整数进行比较)用户在第 ( cin >> materialNum;) 行输入。如果word等于materialNum,那么您可以使用 打印出文件行out << line << ends;

void search(ifstream& inFile){
  string line;
  int word;
  int materialNum;
  istringstream iss;
  cout << "Enter a material number:";
  cin >> materialNum;
  int i=0;

  while(!inFile.eof()){
    // read line by line from the file
    getline(inFile,line);
    if(inFile.good()){
      // read word by word in line and place words in arr
      iss.clear(); // clear out state
      iss.str(line);
      iss >> word;
    }

    if (word == materialNum){
      cout << line << endl;
    }

  }
}

更新:如果您知道文件名,您可以创建一个ifstream对象 ( inFile) 来打开它,然后将它作为参数传递给您的search函数。例如,你可以在你的main函数中做这样的事情

string filename = "example2.dat";
ifstream inFile;
inFile.open(filename, std::ifstream::in);
ml.search(inFile);

推荐阅读