文字列内のすべてのスペースを '%20'で置き換える方法です。一般的にはうまく動作しますが、実行時に 'Run-Time Check Failure#2-S'で終了すると文句を言います。私のforループに問題はありますか?ランタイムチェック失敗2 - S、Visual Studio C++
void replaceSpace(char *s) {
int spaces = 0;
for (int i = 0; i < strlen(s); i++) {
if (s[i] == ' ') {
spaces++;
}
}
// new string that includes overwriting space, and two additional chars
int newLen = strlen(s) + spaces * 2;
s[newLen] = '\0';
for (int i = strlen(s) - 1; i >= 0; i--) {
if (s[i] == ' ') {
s[newLen - 1] = '0';
s[newLen - 2] = '2';
s[newLen - 3] = '%';
newLen -= 3;
}
else {
s[newLen - 1] = s[i];
--newLen;
}
}
}
char test[] = "rep lace Spac e";
replaceSpace(test);
cout << test << endl; //rep%20lace%20Spac%20e
編集:私はcpp shellを介してこれを実行し、妙にすべての問題を持っていませんでした。うん、ビジュアルスタジオ2015を更新して、報告してください。
edit2:Nope、同じエラー。
*見かけ上*未定義の動作の可能性の1つです。 –