0

私は 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;
}

私は本当にいくつかの洞察を使うことができます。どうもありがとうございました!

4

3 に答える 3

7

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;
}
于 2013-05-12T22:28:59.050 に答える
2

覚えていない 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、私のループは文字列を 1 回しか通過しません。)

于 2013-05-12T22:31:27.607 に答える