I'm writing a function to make a string lowercase in C++. It works perfectly fine, but after the last character, it gives a segmentation fault. My code is below:
#include <cctype>
#include <string>
#include <iostream>
using namespace std;
string lowercase(string str)
{
string ans = str;
for (int i=0; i < ans.size(); i++)
{
ans[i] = tolower(ans[i]);
cout << ans[i]<<endl;
}
}
int main()
{
lowercase("TEST");
return 0;
}
What should I do to fix this?
Turning on the warnings, you may spot the error yourself:
Errors:
Your function returns a string, but you have not specified a string to return.
You can fix the problem by returning your ans variable: