如何提取此信息

时间:2015-03-27 03:37:24

标签: c++

我在C ++中经常遇到过这种类型的问题,我觉得这是关于我学习这种技术的时间。我知道它是如何在Java中完成的,但我仍然是C ++的新手。

假设我有一个文本文件,其中包含以下格式的某些日期:

May 3rd, 2014, /
December 4th, 2011, -
January 19th, 200, -
January 1st, 2011, /
March 3rd, 1900, /

每行中的最后一个字符就像一个日期分隔符,如下所示。

如何将它们转换为此格式并写入另一个文本文件:

5/3/2014
12-4-2011
01-19-200
1/1/2011
03/03/1900

这里的重点是字符串操作,而不是文件IO。

我的尝试:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ifstream in;
    string s;
    cout << "\nPlease enter the input file name\n";
    cin >> s;
    in.open(s);
    if (in) {
        // Logic goes here
    }
    else {
        cout << "\nCouldn't locate the file.\n";
    }
    cin.get(); 
    return 0;
}

2 个答案:

答案 0 :(得分:0)

读入和解析此数据的最简单方法可能是使用std::getline()一次读取一行,然后使用std::istringstream将每行转换为流。这样我们就可以使用提取运算符>>来获取值。

有点像这样:

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

int main()
{
    std::ifstream ifs("test.txt");

    if(!ifs)
    {
        std::cout << "ERROR: can't open file." << '\n';
        return 1;
    }

    // working variable for reading in data
    unsigned year;
    unsigned date;
    std::string skip;
    std::string month;
    std::string separator;

    unsigned line_number = 0;

    std::string line;
    while(std::getline(ifs, line)) // read one line at a time
    {
        ++line_number;

        // convert line to input stream
        std::istringstream iss(line);

        // January 1st, 2011, /
        if(!(iss >> month >> date >> skip >> year >> skip >> separator))
        {
            std::cout << "ERROR: parsing: " << line << " line: " << line_number << '\n';
            continue;
        }

        // sanitize input values
        if(year < 1000 || year > 3000)
        {
            std::cout << "WARN: bad year: " << line << " line: " << line_number << '\n';
            continue;
        }

        // process and output in relevant format
        // (change month string to number etc...)

        std::cout << month << separator << date << separator << year << '\n';
    }
}

答案 1 :(得分:0)

你可以改进这一点,但它似乎对我有用,可能会让你开始。

#include <sstream>
#include <iostream>

using namespace std;

void superRobustDateParser(string date){
    string month, crap1, crap2;
    int day, year;

    istringstream iss(date);

    char delimiter = date[date.length() - 1];

    iss >> month >> day >> crap1 >> year >> crap2;

    // I leave this to you to find a more efficient method
    int monthNum;
    if(month == "May")      monthNum = 5; 
    if(month == "December") monthNum = 12; // etc.

    cout << monthNum << delimiter << day << delimiter << year << endl;
}

int main()
{
    string date1 ("May 3rd, 2014, /");
    string date2 ("December 4th, 2011, -");

    superRobustDateParser(date1);
    superRobustDateParser(date2);

    return 0;
}

输出:

 5/3/2014 
 12-4-2011

Ideone:http://ideone.com/P1v14E

相关问题