试图从c++文本文件的单行中提取字符串的一部分



好吧,这是我第二次为我的程序寻求帮助,我知道我几乎得到了它,但我不明白。所以现在我试着写一个程序,让用户以dd/mm/yyyy的格式输入日期,并以月、日、年的形式返回。所以1990年1月1日变成了1990年1月1日。我需要使用一个文本文件,其中有月份的名称旁边的相应数字。所以文本文件的列表看起来像这样:

01January
02February
03March

. .等等......

到目前为止,我有这个:

// 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 ("months.txt");
    cout << "Please enter the date in the format dd/mm/yyyy, include the slashes: " <<      endl;
    cin >> thedate;
    month = thedate.substr( 3, 2 );
    string newmonth;
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            getline (myfile,newmonth);
            newmonth.find(month);

            cout << newmonth << endl;
        }
        myfile.close();
    }
    else cout << "Unable to open file"; 
    return 0;
}

所以我已经能够从用户输入中提取月份,并将其存储为月份,我只是不太确定如何搜索该月份的文本文件,并仅从该行返回月份的名称到一个新字符串。现在,如果我输入02/05/1990,它将输出

05
05
05
05
05
.. for 12 lines. 

我是一个编程新手,所以任何帮助都是感激的。

而且,我的编程课程才上了3周,我们还没有真正学习函数或数组。因此,如果您确实需要提供任何帮助,请避免使用数组和函数。我也明白不从文本文件中读取更容易,但这是我的类从文本文件中读取它的要求,所以我需要它。

谢谢。

string::find函数(您已经使用过)返回搜索字符串(-> month)的位置。您现在可以使用string::substr函数来提取您正在查找的字符串部分。

希望这对开始有帮助。

最新更新