- 老师答疑区
- 帖子详情
老师参与
空串会抛出异常但用例3过不了,下标越界也没法自动捕获异常
澄碧钓徒
发表于2019年07月18日
<p><code class="brush:cpp;toolbar:false" >#include <iostream>
#include <exception>
#include <cstring>
using namespace std;
void my_strcpy(char *d, char *s)
{
int i;
for(i = 0; i < strlen(s); i++)
if(s[i] == ' ')
s[i] = '\0';
for(i = 0; i < strlen(s); i++)
d[i] = s[i];
d[i] = ' ';
}
int main()
{
string d, s;
try{
getline(cin, s);
getline(cin, d);
char dd[81], ss[81];
strncpy(dd, d.c_str(), d.length() + 1); //为什么这里没法主动引发异常?
strncpy(ss, s.c_str(), s.length() + 1);
if(d == ""||s == ""||d.length() > 80||s.length() > 80)
throw exception();
my_strcpy(dd, ss);
cout << dd;
}catch(exception e)
{
cout << "error";
}
}</code></p><p><img src="https://nos.netease.com/edu-image/e145da5ec4a54d4b89f391e3a2dff383.PNG" /></p><p>看到老师在前面一个帖子提示要检查空串,所以我想着判断如果是空串的话就抛出异常(字符数组转字符串不知怎么搞的编译出错,只好这样写了),还有就是第22/23行如果字符数组下标越界为什么也没法主动引发异常直接程序崩溃,还得第24行再判断下长度是否超过80?发现C++对很多异常都不灵敏(包括除零错误都是)?</p>
1
回复