用C ++解析日期字符串

时间:2013-02-19 20:25:50

标签: c++ string parsing date

我的儿子正在学习C ++和他的一个练习,让用户在DD / MM / YYY中输入日期,然后将其输出到月份日,年份

So: 19/02/2013
Output: February 19, 2013.

我想帮助他了解各种方法,但现在我已经把自己搞糊涂了。

getline() std::string::substr() std::string::find() std::string::find_first_of() std::string::find_last_of()

我无法弄清楚这些是非常正确的。

我目前要解析的尝试是:

#include <iostream>
#include <string>

using namespace std;

int main (void)
{
    string date;
    string line;

    cout << "Enter a date in dd/mm/yyyy format: " << endl;
    std::getline (std::cin,date);

    while (getline(date, line))
    {
        string day, month, year;
        istringstream liness( line );
        getline( liness, day, '/' );
        getline( liness, month,  '/' );
        getline( liness, year,   '/' );

        cout << "Date pieces are: " << day << " " << month << " " << year << endl;
    }
}

但我收到的错误如下:

`g++ 3_12.cpp -o 3_12`
`3_12.cpp: In function ‘int main()’:`
`3_12.cpp:16: error: cannot convert ‘std::string’ to ‘char**’ for argument ‘1’ to ‘ssize_t getline(char**, size_t*, FILE*)’`
`3_12.cpp:18: error: variable ‘std::istringstream liness’ has initializer but incomplete type`

4 个答案:

答案 0 :(得分:4)

int day, month, year;
char t;
std::cin >> day >> t >> month >> t >> year;

答案 1 :(得分:1)

你错过了std Regular Expressions Library!我认为这是最安全,最有效的方法。

回到主题,我,因为getline是一个extern "C"函数,你不能使用using namespace std重载它(应该被禁止)顺便说说)。您应该尝试将std添加到所有getline来电。

答案 2 :(得分:1)

对于std::istringstream,您需要:

#include <sstream>

P.S。不要使用using namespace std;。这是一个坏习惯,它最终会让你陷入麻烦。

答案 3 :(得分:1)

错误

  

3_12.cpp:16: error: cannot convert ‘std::string’ to ‘char**’ for argument ‘1’ to ‘ssize_t getline(char**, size_t*, FILE*)’

意味着编译器无法理解这一行:

while (getline(date, line))

dateline都声明为std::string并且getline没有重载 需要两个字符串。编译器猜到你试图调用不属于C ++库的this function(显然,标准库头之一包含stdio.h,这是该函数的来源。)

错误

  

3_12.cpp:18: error: variable ‘std::istringstream liness’ has initializer but incomplete type

表示编译器不知道std::istringstream是什么。您忘记加入<sstream>

如果你想通过std::getline从字符串中提取行,你需要先将它放在字符串流中,就像你在循环中一样。

解析日期并不容易。您不希望用户能够输入44/33/-200并侥幸逃脱。我怎么会这样做:

std::istringstream iss(date); // date is the line you got from the user

unsigned int day, month, year;
char c1, c2;

if (!(iss >> day >> c1 >> month >> c2 >> year)) {
    // error
}
if (c1 != '/' || c2 != '/') { /* error */ }
if (month > 12) { /* error  / }

// ... more of that, you get the idea