I\'m having a problem running this C++ program. I keep getting the error: termin
ID: 3838641 • Letter: I
Question
I'm having a problem running this C++ program. I keep getting the error: terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct null not valid
Aborted (core dumped)
This is the code:
#include <iostream>
#include <cassert>
#include <string>
using namespace std;
typedef int fsm_state;
typedef char fsm_input;
bool is_final_state(fsm_state state)
{
return (state == 3) ? true : false;
}
fsm_state get_start_state(void)
{
return 0;
}
fsm_state move(fsm_state state, fsm_input input)
{
// our alphabet includes only 'a' and 'b'
if (input != 'a' && input != 'b')
assert(0);
switch (state)
{
case 0:
if (input == 'a')
{
return 1;
}
else if (input == 'b')
{
return 0;
}
break;
case 1:
if (input == 'a')
{
return 1;
}
else if (input == 'b')
{
return 2;
}
break;
case 2:
if (input == 'a')
{
return 1;
}
else if (input == 'b')
{
return 3;
}
break;
case 3:
if (input == 'a')
{
return 1;
}
else if (input == 'b')
{
return 0;
}
break;
default:
assert(0);
}
return -1; // Error code
}
bool recognize(string str)
{
if (str == "")
return false;
fsm_state state = get_start_state();
string::const_iterator i = str.begin();
fsm_input input = *i;
while (i != str.end())
{
state = move(state, *i);
++i;
}
if (is_final_state(state))
return true;
else
return false;
}
// simple driver for testing
int main(int argc, char** argv)
{
recognize(argv[1]) ? cout << "1" : cout << "0";
cout<<endl;
return 0;
}
Explanation / Answer
Answer:
If we run the program from command prompt it is expecting some arguments but in codeblocks you didnt provide any so it takes null as argument. Line 20 is failed and assert write the core dump and exits. You can pass arguments in codeblock. Your code expecting string of a's and b's.
Goto project menu and choose "set program arguments and pass string a's and b's.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.