The bulk of the problem is before
and after
are Automatic variables scoped within seperateLine
. As soon as an Automatic variable goes out of scope, it is destroyed. Dead, but not always gone. Maybe the memory used to stored it will be reallocated to something else and maybe it won't. Maybe it looks like it worked, maybe it doesn't. You're lucky in this case: It most certainly does not work or even look like it works.
Using a variable after it has been destroyed is textbook Undefined Behaviour and follows Gump's Law: You never know what you're gonna get.
Passing arrays is a messy business. You can dynamically allocated them and return them as a raw or smart pointer, but in C++ the right answer for an array of char
representing a string is almost always "Use std::string
." Often a few choice expletives are embedded for emphasis.
So, if std::string
is available for use on this assignment, Use the <expletive deleted> std::string
.
The rest of the problems are related to loose math around the boundaries of the array. You need to show a lot of care with a +1 or a -1 on an array index to make sure you don't wander out of bounds. As above, the most direct solution to the potential for bad math is use the <expletive deleted> std::string
.
#include <iostream>
#include <string> // changed headers string.h for c-style strings to string
// for std::string
std::string seperateLine(const std::string &line, // a reference to an immutable std::string
int befOrAf){
const static std::string delimiter = " -> "; // helps reduce magic numbers and makes it
// easier to change the token delimiter
std::string before; // now a std::string
std::string after; // also a std::string
auto loc = line.find(delimiter); // uses std::string's find method to find the arrow
if (loc != std::string::npos) // find returns npos if the arrow was not found
{
before = line.substr(0, loc); // using line's substr method to split the string
after = line.substr(loc + delimiter.size()); // look ma! No magic number!
}
std::cout<<"1 "<< before<<std::endl;
std::cout<<"1 "<<after<<std::endl;
if(befOrAf==0) return before;
else return after;
}
int main()
{
// strings, strings and more strings.
std::string grammer[10]={"","","S -> BaB","","","","","","",""};
std::string seperated = seperateLine(grammer[2],0);
std::cout <<"2 "<<seperated<<std::endl;
seperated = seperateLine(grammer[2],1);
std::cout <<"2 "<<seperated<<std::endl;
std::cout << "3 "<<seperateLine(grammer[2],0) <<std::endl
<<"3 "<<seperateLine(grammer[2],1);
return 0;
}