簡體   English   中英

嘗試從C ++中的文本文件的一行中僅提取字符串的一部分

[英]Trying to extract only part of a string from a single line from a text file in c++

好的,這是我第二次為我的程序尋求幫助,我知道我快到了,但是我無法弄清楚。 所以現在我正在嘗試編寫一個程序,讓用戶以dd / mm / yyyy格式輸入日期,並將其返回為月日期,年份。 因此,01/01/1990成為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函數提取您要查找的字符串部分。

希望這對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM