0
点赞
收藏
分享

微信扫一扫

Linux环境下:解决 C++ std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = unsigned int]:的问题

IT影子 2022-04-01 阅读 55
c++
#include<iostream>
#include<cstring>
using namespace std;
string ans, tar;

//字符串加密
void func(void) 
{
    int n = tar.length();
    for (int i = 0; i < n; ++i) 
    {
        ans[i] = (tar[i] - 29) % 93 +33;
    }
    return;
}
int main(void) 
{
    cin>>tar;
    func();
    printf("%s",ans.c_str());
    return 0;

}

比如上面 这段代码里,运行之后

会报错:

/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libstdc++-v3/include/bits/basic_string.h:1067:
 std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference
 std::__cxx11::basic_string<_CharT, _Traits,
 _Alloc>::operator[](std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>;
 std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference =
 char&; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type
 = unsigned int]: Assertion '__pos <= size()' failed.

我再百度上搜了好久发现没有解决方案;

于是科学上网,搜了一早上

终于

塑料英语翻译一下就是: 字符串是空的,给空字符串填下标,是不合法的;

拿我的案例来说 就是,ans 这个字符串为空,不可以给下标

解决方法是

ans.push_back( (tar[i]-29) % 93 + 33; 

这样就可以了

举报

相关推荐

0 条评论