错误STOL处理()函数++
问题描述:
这是代码我使用:错误STOL处理()函数++
int cap(long n){
long sq = n*n;
string num = to_string(sq),s1,s2;
cout << num;
for(int i=1;i<=num.length();i++){
s1 = num.substr(0,i);
s2 = num.substr(i,num.length()-i);
string::size_type sz=0;
long n1 = stol (s1,&sz,0);
long n2 = stol (s2,&sz,0);
if(n1+n2==n){
return 1;
}
}
return 0;
}
This is the error i get。任何暗示这种类型的错误?
答
循环条件是不对的,你应该设置
for(int i=1;i<num.length();i++){
,程序不会崩溃。不过,我不能声称,如果结果是一个理想的。
答
当i=num.length()
,s2
是空的,因为
s2 = num.substr(i,num.length()-i);
其是相同
s2 = num.substr(i, 0); //for i=num.length()
^~~~~length of substring is zero
然后,该空字符串传递给stol
为s2
,从而导致错误“在抛出'std :: invalid_argument'“
long n2 = stol (s2, &sz, 0);
^~~~~Empty string.
而不是把快照,建议复制 - 粘贴错误消息文本。 –