Trying to extract a certain string from a text file

okay so im new to programming and Ive emailed my prof 3 times to ask for help but she hasnt replied, so hopefully someone here can help me out. I know I nearly got it but I cant figure it out. So right now Im trying to write a program that has the user input the date in the format dd/mm/yyyy and return it as month date, year. So 01/01/1990 becomes January 1st, 1990. I need to use a text file that has the names of the months beside their corresponding numbers. So the list of the text file looks like this:

01January
02February
03March

.. and so on.

So far I have this:

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
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
  string thedate; //string to enter the date
  string month; // this string will hold the month
  ifstream myfile;
 cout << "Please enter the date in the format dd/mm/yyyy, include the slashes: " << endl;
 cin >> thedate; //user inputs date

  month = thedate.substr( 3, 2 );
  string newmonth;

  cout << month << endl;

myfile.open("months.txt");

if(!myfile)
{
	cout << "unable to open file" << endl;
	return 1;
}

getline(myfile, newmonth);

cout << newmonth << endl;

  return 0;
}


I know not using a text file would be a lot easier, but I have to as part of the assignment. I know I have to use string.find() in some way, but I dont know how to get it to work with a text file. I tried to store the month in the format mm in the string month, so I could search for whatever the user enetered. I tried using newmonth.find(month); thinking it would search for the contents of the month string, but it didnt.

Ive also looked through http://www.cplusplus.com/reference/string/string/find/ and I still cant figure it out.

Also, we have learned as far as loops, input output, and if/else/ statements. We havnt learned arrays yet, or user defined functiosn, so if you could stay away from those that would be awesome.
Help would be greatly appreciated!
Last edited on
Here the entire contents of the file is displayed.
But you could easily add an if-statement inside the loop to test for the required value of n and thus determine the corresponding month name.

1
2
3
4
5
6
7
8
    ifstream myfile("months.txt");
    int n;
    string name;
    
    while (myfile >> n >> name)
    {
        cout << "n: " << n << " name: " << name << endl;
    }


Of course a much better solution would be to store the names in an array, and directly lookup the required value.
Last edited on
Topic archived. No new replies allowed.