我正在编写一个函数,用 C++ 将字符串变为小写。它工作得很好,但在最后一个字符之后,它给出了一个段错误。我的代码如下:
#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;
}
我应该怎么做才能解决这个问题?
最佳答案
打开警告,您可能会自己发现错误:
g++ -o main main.cpp -Wall
错误:
main.cpp: In function ‘std::string lowercase(std::string)’:
main.cpp:9:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int i=0; i < ans.size(); i++)
^
main.cpp:14:1: warning: no return statement in function returning non-void [-Wreturn-type]
}
你的函数返回一个字符串,但你没有指定要返回的字符串。
您可以通过返回您的 ans 变量来解决问题:
string lowercase(string str)
{
string ans = str;
for (int i=0; i < ans.size(); i++)
{
ans[i] = tolower(ans[i]);
cout << ans[i]<<endl;
}
return ans;
}
关于c++ - 遍历字符串会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30904558/