2016-12-17 133 views
1

这是代码我使用:错误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。任何暗示这种类型的错误?

+1

而不是把快照,建议复制 - 粘贴错误消息文本。 –

回答

0

循环条件是不对的,你应该设置

for(int i=1;i<num.length();i++){ 

,程序不会崩溃。不过,我不能声称,如果结果是一个理想的。

0

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 

然后,该空字符串传递给stols2,从而导致错误“在抛出'std :: invalid_argument'

long n2 = stol (s2, &sz, 0); 
       ^~~~~Empty string. 

Demo