为什么我的程序在从字符串中读取连字符时会崩溃?

时间:2015-02-05 15:47:59

标签: c++ loops

我必须为我正在上课的课程编写程序。我必须以数字形式(mm-dd-yyyy)取出生日期并将其放入不同的格式(月日,年)。我觉得我的代码是正确的,但每当我的while循环进入连字符时,它就会崩溃。它编译正确,Visual Studio在运行之前不会弹出任何错误,所以我真的不知道出了什么问题。我已经包含了整个代码。此外,此分配还需要使用try / catch块。任何人都可以告诉我为什么这个循环不喜欢检查连字符?提前谢谢。

#include <iostream>
#include <string>

using namespace std;

int get_digit(char c) {return c - '0';}

int main() {

string entry = "";
short month = 0;
int day = 0;
int year = 0;
bool error = false;
int temp = 0;

try {

    cout << "Enter your birthdate in the form M-D-YYYY: ";
    cin >> entry;

    int x = 0;
    do {
        month *= 10;
        temp = get_digit(entry[x]);
        month += temp;
        x += 1;
    } while (entry[x] != '-');
    if (month > 12) {
        throw month;
    }
    x += 1;

    do {
        day *= 10;
        temp = get_digit(entry[x]);
        day += temp;
        x += 1;
    } while (entry[x] != '-'); 
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        if (day > 31) {
            throw day;
        }
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
        if (day > 30) {
            throw day;
        }
    } else {
        if (day > 29) {
            throw day;
        }
    }
    x += 1;

    do {
        year *= 10;
        temp = get_digit(entry[x]);
        year += temp;
        x += 1;
    } while (entry[x] != '\n');
    if ((year % 4) != 0) {
        if (month == 2 && day > 28) {
            throw day;
        }
    }

    switch (month) {
    case 1:
        cout << "January ";
    case 2:
        cout << "February ";
    case 3:
        cout << "March ";
    case 4:
        cout << "April ";
    case 5:
        cout << "May ";
    case 6:
        cout << "June ";
    case 7:
        cout << "July ";
    case 8:
        cout << "August ";
    case 9:
        cout << "September ";
    case 10:
        cout << "October ";
    case 11:
        cout << "November ";
    case 12:
        cout << "December ";
    }

    cout << day << ", " << year << endl;

} catch (short) {

    cout << "Invalid Month!" << endl;

} catch (int) {

    cout << "Invalid Day!" << endl;

}

system("pause");
return 0;

}

1 个答案:

答案 0 :(得分:1)

您的条目字符串中没有换行符,因此x不断增加并导致条目[x]的缓冲区溢出。你需要寻找字符串的结尾:

 do {
        year *= 10;
        temp = get_digit(entry[x]);
        year += temp;
        x += 1;
    } while (entry[x] != '\0');