C++ 尝试从文本文件中读取列表,然后搜索文本文件,并在C++;

C++ 尝试从文本文件中读取列表,然后搜索文本文件,并在C++;,c++,string,find,C++,String,Find,现在我正在写一个程序,它接受用户输入的日期,比如说:1992年4月2日,然后输出日期,比如说:1992年4月2日。与程序中的字符串或其他内容不同,我有一个文本文件,其中的日期列表如下: 1月1日 2月2日 3月3日 。。等等 我知道我必须使用string.find(),但我不确定应该使用哪些参数。到目前为止,我有: // reading a text file #include <iostream> #include <fstream> #include <stri

现在我正在写一个程序,它接受用户输入的日期,比如说:1992年4月2日,然后输出日期,比如说:1992年4月2日。与程序中的字符串或其他内容不同,我有一个文本文件,其中的日期列表如下:

1月1日

2月2日

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;
}
//读取文本文件
#包括
#包括
#包括
使用名称空间std;
int main()
{
string thedate;//输入日期的字符串
string month;//此字符串将保存月份
ifstream myfile(“months.txt”);
日期;
月=日期(3,2);
弦月;
如果(myfile.is_open())
{
while(myfile.good())
{
getline(myfile,newmonth);

cout不需要使用find

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

cout我想我应该以一种不同的方式来组织事情。我从一开始就读取整个文件(显然是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];
}
整数;
std::字符串tmp;
std::矢量月份名称(12);
while(我的文件>>编号){
myfile>>tmp;
月份名称[编号]=tmp;
};
string get_name(int month){
返回月份名称[月份];
}

解释
std::string::find()的参数
非常好。@CaptainObvlious我是编程新手,所以我真的不明白std::npos等在他们的代码中的意思?不管怎样,我都看不到任何解释如何使用字符串作为参数来搜索某个东西的内容。多谢了。只要理解那里发生了什么,因为那里有一个完整的列表是if语句试图将文本文件中的每一行与月份匹配吗?是的,如果您确定前两个字母是数字,并且用户输入两个数字,则比较字符串就足够了,或者您可以在通过atoi将字符串转换为整数后进行比较。