How do I search a .txt file and print related lines in c++?

In my code, I want to have a function that goes through each line in a file and prints out the line if the first word in the sentence contains the number given by the user. For example:

Format of the .txt file:

Each word is separated by a space.

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

Output:

1
2
3
Enter a desired number:17
17 35 "door"
17 34 "car"

How would I go about doing this?

Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include<iostream> 
using std::cerr;
using std::endl;
#include <list>
using namespace std; 
#include <fstream>
using std::ofstream;
#include <cstdlib> // for exit function

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

};



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

 }
Last edited on
grep "^17 " inputFile
FYI: grep is available on Windows, search for "GNU grep windows" or "GnuWin32".
The equivalent command also built into Windows is findstr,
findstr "^17 " file.txt
17 35 "door"
17 34 "car"


grep is better, though. If there is potentially whitespace at the beginning of the line, you can do:
grep "^\s*17 " file.txt

I'm sure there's an equivalent for findstr but I didn't feel like figuring it out.
Last edited on
I'm still confused...how would I be able to place that in my code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;

int main()
{
   int target = 17;
   int first;
// ifstream in( "example2.dat" );
   istringstream in( "17 35 \"door\"   \n"
                     "40 19 \"wall\"   \n"
                     "17 34 \"car\"    \n"
                     "3  9  \"window\" \n" );
   
   for ( string line; getline( in, line ); ) if ( stringstream( line ) >> first && first == target ) cout << line << '\n';
}


17 35 "door"   
17 34 "car"   
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<iostream>
#include <list>
#include <fstream>

class Item
{
public:
    int mesh_no;
    int m_no;
    std::string name;
    
public:
    Item(){};
    Item( std::string aName, int a_m_no, int a_mesh_no  )
    {
        m_no = a_m_no;
        mesh_no = a_mesh_no;
        name = aName;
    }
    
public:
    std::string getName(){ return name;}
    void setName(std::string aName){ name = aName; }
    int getMeshNo(){ return mesh_no; }
    void setMeshNo(int a_mesh_no){ mesh_no = a_mesh_no; }
    int getMNo(){ return m_no; }
    void setMNo(int a_m_no){ m_no = a_m_no; }
};


class MaterialList
{
private:
    std::list <Item> items;
    
public:
    MaterialList(){ };
    
public:
    void add(Item &item){ items.push_back(item); }
    void loadFromFile(std::string file_name)
    {
        Item temp;
        std::ifstream myfile (file_name);
        if (myfile.is_open())
        {
            while ( myfile >> temp.m_no >> temp.mesh_no >> temp.name )
            {
                add(temp);
            }
            myfile.close();
        }
        else std::cout << "Unable to open file";
    }
    
    void printItems(int a_m_no)
    {
        for(auto i:items)
        {
            if(i.m_no == a_m_no)
                std::cout
                << i.m_no << ' '
                << i.mesh_no << ' '
                << i.name << '\n';
        }
    }
    
};

int main()
{
    MaterialList ml;
    ml.loadFromFile("item_2020_10.txt");
    ml.printItems(17);
    return 0;
}


Input data file:

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


Results:

17 35 door
17 34 car
Program ended with exit code: 0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <list>
#include <fstream>

class Item
{
public:
	Item() {};
	Item(const std::string& aName, int a_m_no, int a_mesh_no) : m_no(a_m_no), mesh_no(a_mesh_no), name(aName) {}

	std::string getName() const { return name; }
	void setName(const std::string& aName) { name = aName; }

	int getMeshNo() const { return mesh_no; }
	void setMeshNo(int a_mesh_no) { mesh_no = a_mesh_no; }

	int getMNo() const { return m_no; }
	void setMNo(int a_m_no) { m_no = a_m_no; }

	friend std::ostream& operator<<(std::ostream& os, const Item& it);
	friend std::istream& operator>>(std::istream& is, Item& it);

private:
	int mesh_no = 0;
	int m_no = 0;
	std::string name;
};

std::ostream& operator<<(std::ostream& os, const Item& it)
{
	return (os << it.m_no << ' ' << it.mesh_no << ' ' << it.name);
}

std::istream& operator>>(std::istream& is, Item& it)
{
	return (is >> it.m_no >> it.mesh_no >> it.name);
}

class MaterialList
{
public:
	MaterialList() { };

	void add(const Item& item) { items.push_back(item); }

	bool loadFromFile(const std::string& file_name)
	{
		std::ifstream myfile(file_name);

		if (myfile.is_open()) {
			for (Item temp; myfile >> temp; )
				add(temp);

			myfile.close();
			return true;
		}

		return !!(std::cout << "Unable to open file\n");
	}

	void printItems(int a_m_no)
	{
		for (const auto& i : items)
			if (i.getMNo() == a_m_no)
				std::cout << i << '\n';
	}

private:
	std::list<Item> items;
};

int main()
{
	MaterialList ml;

	if (ml.loadFromFile("item_2020_10.txt"))
		ml.printItems(17);
}

Last edited on
Hello,

What is the format of the file? Can you provide an example. The best way of obtaining the numbers depends upon the format of the data that is used. Ganado's code above, for example, won't extract all the numbers if there is non-numeric data also present.

thanks
alexsunny


That is a quote from one of my previous posts in a different thread! It has nothing to do with this thread as the format is stated in the first post.

PS That post has now been removed!
Last edited on
Topic archived. No new replies allowed.