首页 > 解决方案 > C++ islower() 函数调试断言失败错误

问题描述

感谢大家的帮助,我解决了问题,并在最后为遇到同样问题的人提供了工作代码。

我正在尝试编写一个简单的函数,该函数将字符串变量从无字母字符中清除,并将变量转换为全小写。

例如,
“h4el>lo”到“hello”。
“大”到“大”。

唯一的例外是(')撇号标记,因为像(can't)这样的词。
我编写的代码在正常情况下可以完美运行。

string CleanTheWord(string word)
{
    string cleanWord = "";

    for (int i = 0; i < word.length(); i++)
    {
        if (islower(word[i]))
        {
            cleanWord += word[i];
        }
        else if (isupper(word[i]))
        {
            cleanWord += tolower(word[i]);
        }
        else if (word[i] == 39 || word[i] == 44) //Apostrophe mark
        {
            cleanWord += word[i];
        }
    }
    return cleanWord;
}

问题是我需要将此函数应用于一些大量变量,即使其中大部分没有问题,一些变量也包含不常见的字符。例如,导致“Debug Assertion Failed Error”的奇怪字符串值是:

she�s

我犯的错误是:

Debug Assertion Failed
program: //程序路径
File minkernel\crts\ucrt\src\appcrt\convert\isctype.cpp
Line: 36
expression c>=-1 && c <=255

我希望能够将“she�s”转换为“shes”(删除无字母字符“�”)。
或者,如果不可能,我想至少忽略有问题的单词,这样程序就不会崩溃并正常继续。

--------- 工作代码 ---------

string CleanTheWord(string word)
{
    string newWord = "";        

    for (int i = 0; i < word.length(); i++)
    {
        char control = word[i] < 0 ? 0 : word[i];

        if (isupper(control))
        {
            newWord += tolower(control);
        }
        else if (isalpha(control) || control == '\'')
        {
            newWord += control;
        }
    }

    //cout << "Final result: " << newWord << endl;
    return newWord;
}

标签: c++

解决方案


推荐阅读