如何解决错误:“抛出异常:写访问冲突文本为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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。