【发布时间】:2020-03-13 11:31:34
【问题描述】:
如果这是重复的,我很抱歉。我试图找到一个类似但没有得到解决方案的问题。当我询问用户是否想再次输入时,我收到以下错误:“libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string”。如果您输入“N”,则程序结束,但是当您输入“Y”时,它会给我上面的错误。我的程序向用户询问格式为:(2019 年 12 月 25 日)的日期,并将其转换为格式:(MM/DD/YYYY)。代码有效,但我在循环时遇到了一个错误。
这是我的代码:
#include <iostream>
#include <string>
using namespace std;
void getDate(string &mdy){
cout<<"Enter Any Date in Format: (December 25th, 2019) ";
getline(cin, mdy);
}
void extract (string &mdy, string &m, string &d, string &y){
int startIndex, endIndex, endIndexDay, startIndexDay, startIndexYear, endIndexYear;
startIndex = 0;
endIndex = mdy.find(' ');
startIndexDay = ((endIndex - startIndex) +1);
endIndexDay = mdy.find(',');
startIndexYear = (endIndexDay +2);
endIndexYear = mdy.find(' ');
m = mdy.substr(startIndex, endIndex - startIndex);
d = mdy.substr(startIndexDay, (endIndexDay - startIndexDay) - 2);
y = mdy.substr(startIndexYear, endIndexYear - startIndexYear);
}
void convertDigits(string &mdy, string &d, string &y, int &dInt, int &yInt){
dInt = stoi(d);
yInt = stoi(y);
}
void convertMonths(string &mdy, string &m, int &mInt, int &dInt, int &yInt){
if (m == "january" || m == "January")
mInt = 1;
else if (m == "febraury" || m == "February")
mInt = 2;
else if (m == "march" || m == "March")
mInt = 3;
else if (m == "april" || m == "April")
mInt = 4;
else if (m == "may" || m == "May")
mInt = 5;
else if (m == "june" || m == "June")
mInt = 6;
else if (m == "july" || m == "July")
mInt = 7;
else if (m == "august" || m == "August")
mInt = 8;
else if (m == "september" || m == "September")
mInt = 9;
else if (m == "october" || m == "October")
mInt = 10;
else if (m == "november" || m == "November")
mInt = 11;
else if (m == "december" || m == "December")
mInt = 12;
else
cerr<<"Error...Please check your spelling and the date format and try again.";
cout<<endl<<"Another Date Format is: "<<dInt<<"/"<<mInt<<"/"<<yInt<<endl; //Outputting the new date.
}
int main() {
string date, month, day, year;
int monthInt, dayInt, yearInt;
char tryAgain = 'Y';
while (tryAgain =='Y' || tryAgain == 'y'){
getDate(date);
extract(date, month, day, year);
convertDigits(date, day, year, dayInt, yearInt);
convertMonths(date, month, monthInt, dayInt, yearInt);
cout<<"Try Again? Type Y or N: ";
cin>>tryAgain;
}
return 0;
}
【问题讨论】:
-
为我工作..这是什么编译器?
-
我正在使用 cLion
-
CLion 不是编译器,它是 IDE...我假设您使用的是 gcc/g++ .. 在这种情况下,问题一定出在其他地方。
-
是的,对不起,我使用的编译器是 gcc 或 g++
-
std::out_of_range: basic_string表示,您正在访问std::string后面的字符。不确定它发生在哪里,但是:混合流输入>>和std::getline()需要格外小心。因此,我会对此进行调试和检查。
标签: c++ string loops while-loop