c++ - 遍历字符串会导致段错误

标签 c++ string replace lowercase

我正在编写一个函数,用 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/

相关文章:

java - String.format() 在参数为空字符串时添加 2 个空格

c++ - 试图让简单的 ODB 'hello' 程序工作

c++ - 如何通过交叉编译构建调试 Qt dll 问题?

string - 在 Raku 中不创建字符串上下文的情况下进行插值?

Javascript 查找和替换变量

html - 使用 sed 将 URL 转换为 HTML 链接?

php - 替换字符串php中的尴尬字符

c++ - 没有管理员权限的 SFML 1.6

c++ - SFML + 固定时间步 = 滞后?

c# - 使用 C# 在字符串中查找文本