错误:“抛出异常:写访问冲突文本为0x

问题描述

我需要编写一个函数,该函数将一个字符中的单词开头的每个字母都大写(即"hello. this is a test""Hello. This Is A Test"中)。我的老师给了我我需要使用的函数的标题以及它的return语句。

当我运行它时,它显示出错误“写访问冲突”,我真的不明白为什么。我在Internet上浏览了很多东西,但是找不到任何与我的情况类似的东西。

这是我的老师问的:

实施toTitleCase(字符*文本)方法,将接收到的文本转换为标题大小写格式

  • 所有单词均以大写字母开头
  • 例如:“你好。这是测试”变成“你好。这是测试”

此外,我正在VS 2019 for C ++中使用Google Test对其进行测试,测试功能为:

TEST(TestTitleCase,RightTest) {
    char* text = "hello. this is a test";
    char* newText = toTitleCase(text);
    ASSERT_TRUE(newText != nullptr);
    EXPECT_EQ(strcmp(newText,"Hello. This Is A Test"),0);
}

这就是我写的:

char* toTitleCase(char* text) {

    text[0] = text[0] - 32;  //the error is here
    for (int i = 1; i < strlen(text); i++)
        if ((text[i] != ' ') && (text[i - 1] == ' '))
            text[i] = text[i] - 'a' + 'A';  //when I comment the first line I also get an error here
    cout << text;
    return nullptr;
}

解决方法

TEST()中,您有text指向字符串文字 1 ,该字符串存储在只读存储器中。您正在将text传递到toTitleCase()

1:但是,由于使用了nullptr,因此您似乎正在使用C ++ 11编译器,并且在C ++ 11及更高版本中分配窄字符串文字是非法的如图所示,指向非常量char*指针。

toTitleCase()中,您试图修改text参数所指向的字符串的内容。但是text指向的是只读字符串文字,因此存在访问冲突。

要解决此错误,您可以更改此行:

char* text = "hello. this is a test";

为此:

char text[] = "hello. this is a test";

这将创建字符串文字数据的可写副本


话虽如此,如果可能的话,您应该使用std::string而不是char*,例如:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

...

TEST(TestTitleCase,RightTest)
{
    string text = "hello. this is a test";
    string newText = toTitleCase(text);
    EXPECT_EQ(newText,"Hello. This Is A Test");
}

char upperCase(char c)
{
    return static_cast<char>(toupper(static_cast<unsigned char>(c));
}

string toTitleCase(string text)
{
    text[0] = upperCase(text[0]);
    for (size_t i = 1; i < text.size(); i++) {
        if ((text[i] != ' ') && (text[i - 1] == ' '))
            text[i] = upperCase(text[i]);
    }
    cout << text;
    return text;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...