0

因此,现在我正在尝试编写一个程序,该程序接受用户输入的日期,例如:02/04/1992,并输出如下日期:1992 年 4 月 2 日。而不是将相应的日期作为字符串或其他内容在程序中,我有一个文本文件,其中包含这样的列表中的日期:

011月

02二月

3月3日

.. 等等。

我知道我必须使用 string.find(),但我不确定我应该使用什么参数。到目前为止,我有这个:

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

            cout << newmonth.find() << endl;

        }
        myfile.close();
    }

    else cout << "Unable to open file"; 

    return 0;
}

我已经在线检查了查找功能,但我仍然不明白我将使用哪些参数。现在在我的程序中,格式为 mm 的月份存储在字符串月份中;我不知道如何在文本文件中搜索月份内的内容;并返回该行的其余部分。例如,05 将变为 May。我还没有学过数组,所以如果我能远离那些,那就太棒了。

谢谢。

4

2 回答 2

0

不需要使用查找。

while ( myfile.good() )
{
    getline (myfile,newmonth);
    if ( newmonth.substr(0,2) == month) {
        cout << newmonth.substr(2) << endl;
    }
}
于 2013-06-01T21:53:26.970 回答
0

我想我会以不同的方式组织事情。我会在开始时读入整个文件(显然是 12 行),使用数字来确定数组中存储相关字符串的位置。然后,当用户输入日期时,您只需使用他们的数字索引到该数组而不搜索它。

int number;
std::string tmp;

std::vector<std::string> month_names(12);

while (myfile >> number) {
   myfile >> tmp;
   month_names[number] = tmp;
};

std::string get_name(int month) { 
    return month_names[month];
}
于 2013-06-01T23:11:54.237 回答