How to find specific value in text file

I noticed that if i put the date as shown below, it return a correct line. But what if i asked the user to input certain value for year, month and date and return the input line?

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ifstream  myfile("weather.txt");
string line ;

bool found = false;
while( std::getline( myfile, line ) && !found)
{
if(line.find("2015-11-13") != string::npos) //HERE!
{ 
cout << line << endl;
found = true;
}
}

if (!found)
cout << "NOT FOUND";
return 0;
}
Something like this?
1
2
3
4
5
6
7
8
string d, m, y;
cout << "Enter y m d: ";
cin >> y >> m >> d;
string search  = y + "-" + m + "-" + d;

// ...

if(line.find(search) != string::npos) //... 
Last edited on
yea i think so.. tried your code but i got mingw error
y + "-" + m + "-" + d should be maybe y + '-' + m + '-' + d
We haven't learned C++ syntax yet so maybe I'm wrong, but in both cases it works for me :D

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream myfile("weather.txt");
    string line, d, m, y;
    cout << "Enter d: ";
    cin >> d;
    cout << "Enter m: ";
    cin >> m;
    cout << "Enter y: ";
    cin >> y;
    string search  = y + '-' + m + '-' + d;
    /* alternative:
    string search = "";
    search.append(y);
    search.append("-");
    search.append(m);
    search.append("-");
    search.append(d);*/
    bool found = false;
    while(std::getline(myfile, line) && !found)
    {
        if(line.find(search) != string::npos)
        { 
            cout << line << endl;
            found = true;
        }
    }
    if (!found)
        cout << "NOT FOUND";
    return 0;
}
Last edited on
Found a new solution.. i declare date as string instead of declare one by one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
        ifstream myfile("weather.txt"); //open file
	getline(myfile, line); 
	{
		cout <<"\n\n     Format (year-month-date)";
		cout <<"\n     Enter the date you desired :  " ;
		cin >> date;
		
		bool found = false;
		while(getline( myfile, line ) && !found)
			{
			if(line.find(date) != string::npos) 
				{ 											
					found = true;
				}
			}

		if (!found){
		    Sleep(2000);
		    cout << "\n\n   NOT FOUND" << endl; } 

Topic archived. No new replies allowed.