问题存储日期c ++

时间:2015-09-28 06:46:23

标签: c++ date scanf

我有一节课,学生。 它包含一个私人会员' dob' 我想将字符串dob设置为正确的日期。 我应该验证输入,我试图使用scanf,但我不确定为什么我的输出关闭。

void Student::getBday(){
    int mm, dd, yyyy;
    printf("Date of Birth?\n");
    scanf("%d/%d/%d", &mm, &dd, &yyyy);
    dob = mm + '/' + dd + '/' + yyyy;
}

这是我的打印功能:

void Student::printStudent(){
    cout.flush();
    cout << endl;
    cout << "Student: " << lastName << ", " << firstName << endl;
    cout << "Student ID: " << ID << endl;
    cout << "Gender: " << gender << endl;
    cout << "Status: " << status << endl;
    cout << "Date of Birth: " << dob << endl;
    cout << "GPA: " << gpa << endl;
    cout << endl;
}

我的输出:

LastName?
Bar
FirstName?
Foo
Gender?
M
Status?
Freshman
Date of Birth?
12/21/2012
GPA?
3.5
ID?
12345678
12345678

Student: Bar, Foo
Student ID: 12345678
Gender: M
Status: Freshman
Date of Birth: [
GPA: 3.5

Press any key to continue . . .

修改

终于搞定了。谢谢所有帮助。我选择了这个答案,因为它帮助我转换,但每个人都帮助我理解我的连接问题。

2 个答案:

答案 0 :(得分:1)

这是您使用scanf导致问题的方式。

应该更像是

QLabel * lpQLabel = new QLabel(this); // lpQLabel is owned by `this`

修改

以下是sprinf(...)

的示例
...
printf ("Date of Birth?");
scanf("%d/%d/%d", &mm, &dd, &yyyy); 
...

答案 1 :(得分:1)

尝试#include <sstream>,然后设置dob,如下所示:std::ostringstream oss; oss << mm << '/' << dd << '/' << yyyy; dob = oss.str();。如果您希望它看起来更好,请使用Google std::setwstd::setfill将日/月数字填充为2位数。

您还应该检查输入错误:

if (scanf("%d/%d/%d", &mm, &dd, &yyyy) != 3)
{
    std::cerr << "twit!  call that a date???\n";
    exit(1);
}

(正如molbdnilo评论的那样,您当前的问题是您要从日期的各个部分添加提取编号,然后将这些数字与两个'/'字符的ASCII值一起添加:相反,您需要连接字符串表示字符串流的那些值的表示。)