[英]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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.