Home > Net >  String std::logic_error: basic_string::_S_construct null not valid
String std::logic_error: basic_string::_S_construct null not valid

Time:11-03

#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;
}

The error pool statement is:

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

CodePudding user response:

string S = 0; is interpreted as std::string S{nullptr}; which is forbidden.

Just write string S; instead.

CodePudding user response:

After you fix the hard error of string S = 0;, you also have undefined behaviour, as you use T without initialising it.

Also using namespace std; pulls in far too many names, 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;
}
  • Related