I am a newbie to C++ and I've tried to write a simple string reverse program. When I compile it, everything is OK, but when I run it, I get the following error:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
Aborted (core dumped)
What I am doing wrong? Here is my code.
#include <iostream>
using namespace std;
string reverse_string(char* argv[], int i);
int main(int argc, char* argv[])
{
for (int i = 0; i < argc; i++)
{
cout << reverse_string(argv, i) << endl;
}
return 0;
}
string reverse_string(char* argv[], int i)
{
string arg = argv[i + 1];
string output;
int length = arg.length();
for (int index = 1; index <= length; index++)
{
output += arg[length-index];
}
return output;
}
This: argv[i + 1] in the construction of your reversed string should be argv[i] and the main loop should be for (i=1; i<argc; ++i)
And there are simpler ways to reverse a string:
std::string reverse_string(char* argv[], int i)
{
std::string arg = argv[i];
return std::string(arg.rbegin(), arg.rend());
}
This error message
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
means that you are trying to call constructor of std::string passing as argument pointer NULL. The problem is that *(argv + argc) is NULL pointer.
Also take into account that you must include header <string>
As for the reverse function then it can be written much simpler then that of you. First of all it could have only one parameter of type const char *
For example
#include <iostream>
#include <string>
std::string reverse_string( const char* s );
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
std::cout << argv[i] << " -> " << reverse_string( argv[i] ) << std::endl;
}
return 0;
}
std::string reverse_string( const char* s )
{
std::string arg( s );
return std::string( arg.rbegin(), arg.rend() );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With