2013-05-30 26 views
0

好吧,这是我第二次寻找我的程序帮助,我知道我几乎得到它,但我无法弄清楚。所以,现在我试图编写一个程序,用户输入格式为dd/mm/yyyy的日期,并将其作为月份日期,年份返回。因此,01/01/1990成为1990年1月1日。我需要使用一个文本文件,其中包含相应数字旁边的月份名称。所以文本文件的列表如下所示:试图从C++中的文本文件中只从一行中提取字符串的一部分

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; 
} 

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

05 
05 
05 
05 
05 
.. for 12 lines. 

我是新来编程,所以任何帮助表示赞赏。另外,我的编程课程只有3周左右,我们还没有真正学过函数或数组。所以如果你有任何帮助提供,请避免数组和功能。我也明白,从文本文件中读取文本比较容易,但是这是我的课程从文本文件中读取它的要求,所以我需要它。

谢谢。

+5

你有没有试过要求同学或教授的帮助?我们不是真的在这里为你做功课。特别是随意的限制,如“不需要数组或功能”。 –

+0

该循环应该是'while(std :: getline(myfile,newmonth))'。您可能也对'find'的文档感兴趣:http://en.cppreference.com/w/cpp/string/basic_string/find – chris

+1

没有数组?没问题,你应该使用'std :: vector'来代替。 – syam

回答

0

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

希望有助于开始。

相关问题