一、0.8的代码

#include<bits/stdc++.h>
using namespace std;

int  main()
{
    string str;
    while(cin>>str)
    {
        int n;
        cin>>n;
        int len=str.size();
        if( n>len || n<0 )
        {
            cout<<"-1"<<endl;
        }

        if( 0==n )
        {
            break;
        }

        for(int i=0; i<=(len-n); ++i)
        {
            string temp;
            temp=str.substr(i,n);
            if( i!=(len-n) )
            {
                cout<<temp<<" ";
            }
            else
            {
                cout<<temp<<endl;
            }

        }
    }
}
运行错误:请检查是否存在数组、列表等越界非法访问,内存非法访问等情况
case通过率为80.00%
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr: __pos (which is 7) > this->size() (which is 6)

二、解决bug

  • 上面,好像逻辑OK,但是越界了,原因是,无论n>0还是n<len后面还会使用substr
  • 这个bug太难复现了
#include<bits/stdc++.h>
using namespace std;

int  main()
{
    string str;
    while(cin>>str)
    {
        int n;
        cin>>n;
        int len=str.size();
        if( n>len || n<0 )
        {
            cout<<"-1"<<endl;
        }
        else if( 0==n )
        {
            break;
        }
        else
        {
            for(int i=0; i<=(len-n); ++i)
            {
                string temp;
                temp=str.substr(i,n);
                if( i!=(len-n) )
                {
                    cout<<temp<<" ";
                }
                else
                {
                    cout<<temp<<endl;
                }
            }

        }

    }
}