在 LTestStr.exe: 0xC0000005:访问冲突写入位置0x00770000 0x008F1D0D引发异常。
在运行时尝试将一个数组中的一个字符放入另一个数组时会出现此错误。
输入字符串后立即发生错误,它不会关闭程序,只是"暂停"它。
#include "stdafx.h"
#include <iostream>
#include <cstring>
int main()
{
using namespace std;
char test[20];
char result[20];
int i = 0;
cout << "Enter a string without symbolic characters: ";
cin.get(test, 20);
for (i; (test[i] != '?' || test[i] != ' '); i++)
{
result[i] = test[i]; //Exception gets thrown here
}
if (strcmp(result, test) != 0)
{
cout << "Fail.";
}
else
{
cout << result << endl;
cout << "Success.";
}
return 0;
}
我已经用评论标记了异常被抛出的位置。
该程序仅用于限制用户可以输入的内容,纯粹用于测试。但我不明白为什么这不起作用。
可能有一些功能可以为我做到这一点,但我仍在学习语言,我只是对尝试和测试我可以用循环等做什么感兴趣。
编辑
在提出建议后,我更改了 AND 运算符的 OR 运算符,并且不再收到错误。但是,我确实有一些非常奇怪的行为。
图片
test[i] != '?' || test[i] != ' '
总是true
,所以你最终会超过数组的边界,因为i++
增量太远。
您是否想要一个&&
来代替||
?
最后,你需要插入一个显式的 NUL 终止符来result
,否则输出将是未定义的。一种简单的