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

Why is my program crashing when it reads a hyphen from a string?

本文关键字:连字符 读取 崩溃 字符串 我的 程序 为什么      更新时间:2023-10-16

我必须为正在学习的一个类编写一个程序。我必须以数字形式(mm-dd-yyyy)输入出生日期,并将其转换为不同的格式(月、日、年)。我觉得我的代码是正确的,但每当do-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;
}

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

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