尝试从文本文件中读取列表,然后搜索文本文件,并在c++中提取字符串

Trying to read off a list from a text file, then search the text file, and extract a string in C++

本文关键字:文本 文件 字符串 并在 c++ 提取 搜索 列表 读取 然后      更新时间:2023-10-16

所以现在我正在尝试编写一个程序,它接受用户输入的日期,如:02/04/1992,并输出日期如下:1992年4月2日。与在程序中以字符串或其他形式显示相应的日期不同,我有一个文本文件,其日期以列表形式显示,如下所示:

1月01

2月02

3月03

. .等等......

我知道我必须使用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的月份存储在字符串month中;我不知道如何在文本文件中搜索month;里面的内容,并返回该行的其余部分。例如,05会变成May。我还没学过数组,所以如果我能远离数组就太棒了。

谢谢。

不需要使用find.

while ( myfile.good() )
{
    getline (myfile,newmonth);
    if ( newmonth.substr(0,2) == month) {
        cout << newmonth.substr(2) << endl;
    }
}

我想我会以不同的方式组织事情。我在开始时读取了整个文件(显然是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];
}