c++的访问冲突
Access violation with C++
我对C语言有点生疏,我被要求编写一个快速的小应用程序,从STDIN中获取字符串,并将字母'a'的每个实例替换为字母' C '。我觉得我的逻辑是正确的(很大程度上要感谢阅读这个网站上的帖子,我可能会补充),但我不断得到访问违反错误。
下面是我的代码:#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
printf("Enter a string:n");
string txt;
scanf("%s", &txt);
txt.replace(txt.begin(), txt.end(), 'a', 'c');
txt.replace(txt.begin(), txt.end(), 'A', 'C');
printf("%s", txt);
return 0;
}
我真的需要一些洞察力。非常感谢!
scanf不知道std::string是什么。你的c++代码应该是这样的:
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
cout << "Enter a string:" << endl;
string txt;
cin >> txt;
txt.replace(txt.begin(), txt.end(), 'a', 'c');
txt.replace(txt.begin(), txt.end(), 'A', 'C');
cout << txt;
return 0;
}
请不要把任何记不太清的C语言扯进来。下面是一个可能的c++解决方案:
#include <string>
#include <iostream>
int main()
{
for (std::string line;
std::cout << "Enter string: " &&
std::getline(std::cin, line); )
{
for (char & c : line)
{
if (c == 'a') c = 'c';
else if (c == 'A') c = 'C';
}
std::cout << "Result: " << line << "n";
}
}
(当然可以使用std::replace
,但我的循环只遍历字符串一次)
看来你把c和c++混在一起了
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Enter a string << endl;
string txt;
cin >> txt;
txt.replace(txt.begin(), txt.end(), 'a', 'c');
txt.replace(txt.begin(), txt.end(), 'A', 'C');
cout << txt << endl;
return 0; }
不要担心,这是一个常见的错误,把c和c++混在一起,也许看看这里的输入链接描述是一个很好的开始
相关文章:
- 写入位置0x0000000C时发生访问冲突
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 链表中写入访问冲突的未知原因
- C++中的openCV Mat访问冲突
- C++尝试深度复制唯一指针时出现内存访问冲突
- C++ 中动态二维数组的访问冲突
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 写入访问冲突异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 读取访问冲突.这0xCDCDCDCD
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 插入数组时违反写访问冲突
- 使用 ReadProcessMemory 获取字符串值的访问冲突
- 尝试通过共享指针使用变量时读取访问冲突
- 堆栈上的 C++ 访问冲突写入异常
- 引发异常:写访问冲突. temp 为 nullptr
- 将静态字符数组中的字符分配给动态分配的字符数组 - 访问冲突
- 在C++中删除双向链表的头节点后出现访问冲突异常
- C++ 读取访问冲突,0xCDCDCDCD