gpt4 book ai didi

c++ - 抛出异常 : write access violation. _My_data 为 0x7001AC

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:08 25 4
gpt4 key购买 nike

我是 C++ 初学者。我尝试编写获取特定字符串的代码,例如 - "there1hello0" .我试着按照这条规则从中造句:

每个单词都以一个数字结尾,表示它在句子中的位置。因此句子是:"hellothere" .

我的代码:

void analyze() 
{
string Given = "there1hello0";
int flag = 0;
string word = "";
string Display[2];

for (int i = 0; i <= Given.length(); i++) {
if (isdigit(Given[i])) {
for (int x = flag; x <= 1; x--) {
word += Given[i - x];
}
Display[(int)Given[i]] = word;
word = "";
flag = 0;
}
else {
flag++;
}
}

for (int z = 0; z <= 1; z++) {
cout << Display[z];
}
}

int main()
{
analyze();
system("pause");
return 0;
}

我已经包含了 <string><iostream>库和使用的命名空间标准。

不知为何,我想不通。因为我无法真正理解异常,所以我的代码无法运行并抛出以下内容:

Exception thrown: write access violation. _My_data was 0x7001AC.

如有任何帮助,我们将不胜感激。

最佳答案

您可以使用调试器轻松跟踪错误。我强烈建议学习如何使用它。
但是无论如何,您的代码有很多问题。首先,您应该了解 for 循环的工作原理以及您应该如何遍历字符串。

for (int i = 0; i <= Given.length(); i++)

应该是

for (int i = 0; i < Given.length(); i++)

所以改为<=你应该使用 < .因为如果 n 是长度,则字符串的最后一个元素存储在位置 n-1 上,因为您是从 0 开始迭代的。

也在你的内部循环中

for (int x = flag; x <= 1; x--) {

你正在向下迭代,所以你应该比较 x >= 1而不是 x <= 1 .

还有 (int)Given[i]返回存储在 Given[i] 中的 char 的 ASCII 值.例如,如果 Given[i]='0'然后(int)Given[i]将返回 char '0' 的 ascii 值,即 48 而不是您想象的 0。您可以在此处找到有关此问题的更多信息:Convert char to int in C and C++ .

关于c++ - 抛出异常 : write access violation. _My_data 为 0x7001AC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49885966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com