저는 수업을 듣기 위해 프로그램을 작성해야합니다. 나는 출생 날짜를 숫자 형식 (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;
}
그리고 충돌 오류가 무엇입니까? 예외가 있습니까? – RvdK
** 디버그 ** 및 ** 단계 **에서 코드를 실행 했습니까? 그렇다면 어떤 라인에서 문제가 발생합니까? – Vinzenz
try catch를 꺼내거나 예외를 잡아 내서 어떤 예외가 던져 졌는지 확인하십시오. – mcraen