c++的访问冲突

Access violation with C++

本文关键字:访问冲突 c++      更新时间:2023-10-16

我对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++混在一起,也许看看这里的输入链接描述是一个很好的开始