简体   繁体   中英

Access violation with C++

I am a bit rusty with the C languages, and I have been asked to write a quick little application to take a string from STDIN and replace every instance of the letter 'a' to a letter 'c'. I feel like my logic is spot on (largely thanks to reading posts on this site, I might add), but I keep getting access violation errors.

Here is my code:

#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;
}

I can really use some insight. Thank you very much!

scanf doesn't know what std::string is. Your C++ code should look like this:

#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;
}

Please don't drag any half-remembered bits of C into this. Here's a possible C++ solution:

#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";
    }
}

(You can of course use std::replace , though my loop only goes through the string once.)

it seem your are mixing c with 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; }

don;t worry, It is a common mistake, to mix c with c++, maybe looking at enter link description here is a good start

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM