从字符串中取出一个错误的C ++片段

时间:2017-01-23 20:49:33

标签: c++ function slice string-concatenation

我正在尝试编写一个函数,该函数从用户指定的点(n)开始的1000个字符串联的素数字符串中输出5个字符的字符串。我终于得到了程序本身的编译,但我似乎遇到了程序本身的错误,我们还没有被教过的工具可以帮助我看到我的问题在我的编程中。我认为问题在于获取和显示切片本身,而不是连接的字符串......但是,我可能/可能是错的。任何建议将不胜感激。

-Apiring Computer Crim。主要

#include<iostream>
#include<string>


std::string get_concatenated_primes()
{
        unsigned int base, test, cap=1000, prime=0;
        std::string plist;
        for (base=0; base < cap; ++base)
        {
            for (test=2; test < base; ++test)
            {
                    if (base % test == 0)
                            break;
                    else
                    {
                            prime=1;
                    }
            }

            if (prime == 1 &&  plist.length() < 1000)
            {
                    plist += base;
            }
    }
    return plist;
}


std::string get_slice_of_5(const std::string concat_primes, const unsigned int n)
{
        std::string slice;
        slice = concat_primes.substr (n, 5);
        return slice;
}


int main()
{
    unsigned int n;

    while(std::cin >> n)
    {
        std::string concat_primes = get_concatenated_primes();
        std::cout << get_slice_of_5(concat_primes, n) << std::endl;
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

在抛出&#39; std :: out_of_range&#39;的实例后终止调用   what():basic_string :: substr:__ post(998)&gt; this-&gt; size()(即997)

我没有得到你想做什么,但是你应该检查concat_primes是否有比n更多的字符。