Given a string, I have to return the middle character or characters(if the string is even) of the string. This is what I came up with.
#include <iostream>
#include <string>
std::string input = "test";
std::string get_middle(std::string input)
{
if (input.size() % 2 == 0) {
input.erase(input.begin(), (input.size() / 2) - 1);
input.erase(input.begin() + 2, (input.size() / 2) - 1);
}
else {
input.erase(input.begin(), (input.size() - 1) / 2);
input.erase(input.begin() + 1,(input.size() - 1) / 2);
}
return input;
}
The errors have always been at the input.begin() or input.erase() part. Curiously, this example I found on http://www.cplusplus.com/reference/string/string/erase/ works even when it looks the same as mine:
#include <iostream>
#include <string>
int main ()
{
std::string str ("This is an example sentence.");
std::cout << str << '\n';
// "This is an example sentence."
str.erase (10,8); // ^^^^^^^^
std::cout << str << '\n';
// "This is an sentence."
str.erase (str.begin()+9); // ^
std::cout << str << '\n';
// "This is a sentence."
str.erase (str.begin()+5, str.end()-9); // ^^^^^
std::cout << str << '\n';
// "This sentence."
return 0;
}
What seems to be the issue here?