为什么我的程序在从字符串中读取连字符时会崩溃
Why is my program crashing when it reads a hyphen from a string?
我必须为正在学习的一个类编写一个程序。我必须以数字形式(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] != ' ');
相关文章:
- 尝试一次将单个字符读取到大小不确定的数组中
- C++将 txt 数据和字符读取到 2D 数组中
- C++ UTF-8 瑞典语字符读取为 ASCII
- 字符串重复替换为连字符 C++
- C++逐个字符读取二进制文件字符
- 如何使用 STL C++读取文件和保存连字符
- 逐个字符读取文件并使用<cctype>
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- C 如何通过特定n字符读取TXT文件的值
- 如何使用4个字符读取C 的文本文件
- 使用C++中的字符读取具有文件 I/O 的文件
- 是否可以从C 中的文件中的线中的特定字符读取
- 将字符读取到数组
- 如何在 c++ 中逐个字符读取文件并通过 array_name[index] 访问它
- 如何从文本文件中读取,C++中逐个字符读取
- 如何将多个字符读取合并为std::向量
- 用连字符替换字符串中的文本
- 为什么我的程序在从字符串中读取连字符时会崩溃
- 在 c++ 中逐个从文件字符读取
- C++ 中有多少个方法逐个字符读取字符串,以对每个字符执行所需的操作