【问题标题】:String std::logic_error: basic_string::_S_construct null not valid字符串 std::logic_error: basic_string::_S_construct null 无效
【发布时间】:2021-12-16 23:41:41
【问题描述】:
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string S = 0; 
    int T,R;
    
    cin >> S >> R;
    
    for(int i = 0; i < T; i++)
    {
        for(int k = 0; k < S.length(); k++)
        {
            for(int j = 0; j < R; j++)
            {
                cout << S[k];
            }
        }
        cout << endl;
    }
    
    return 0;
}

错误池语句为:

terminate called after throwing an instance of 'std::logic_error'
   what(): basic_string::_S_construct null not valid

【问题讨论】:

  • 有趣的是,您会尝试在不必要的情况下将 std::string 初始化为 0,但不初始化其他变量,这是一种很好的做法。由于T 未初始化且从未分配,因此它可能不是用作循环限制的最佳选择。

标签: c++ stl


【解决方案1】:

string S = 0; 被解释为std::string S{nullptr};,即forbidden

改写string S;即可。

【讨论】:

  • 接下来的问题是T未初始化。
【解决方案2】:

修复string S = 0; 的硬错误后,您还会有未定义的行为,因为您使用T 而不初始化它。

还有using namespace std; 引入了太多名字,you shouldn't do it

#include <iostream>
#include <string>

int main()
{
    std::string S; 
    int R;
    
    std::cin >> S >> R;
    
    for(int i = 0, T = 1/*???*/; i < T; i++)
    {
        for(char c : S)
        {
            for(int j = 0; j < R; j++)
            {
                std::cout << c;
            }
        }
        std::cout << std::endl;
    }
    
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-13
    • 2017-04-11
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 2019-02-08
    • 2019-06-23
    相关资源
    最近更新 更多