我一直在學習Codecademy的C 課程,我已經學到了最后,但我對最后一項任務感到困惑。
我們必須創建一個程式,將選定的單詞過濾為 "臟話",并將其替換為選定的任何字符。
我已經在Visual Studio中撰寫了代碼,可以看到以下內容 main.cpp
#include <iostream>
#include <string>
#include "function.h"
int main()
{
std::string word = "broccoli"。
std::string sentence = "我有時吃西蘭花。"。
bleep(word, sentence)。
for (int i = 0; i < sentence.size(); i ) {
std::cout << sentence[i];
}
std::cout << "
"。
}
functions.cpp
#include <iostream>
#include <string>
#include "function.h"
void asterisk(std::string word, std::string &text, int) {
for (int k = 0; k < word.size(); k ) {
text[i k] = '*';
}
}
void bleep(std::string word, std::string &text){
for (int i = 0; i < text.size(); i ) {
int match = 0;
for (int j = 0; j < word.size(); j ) {
if (text[i j] == word[j]) {
匹配 。
}
}
if (match == word.size() ) {
asterisk(word, text, i)。
}
}
functions.h
#pragma once
void bleep(std::string word, std::string &text)。
void asterisk(std::string word, std::string &text, int i);
現在,當我在Visual Studio中運行這段代碼時,我得到一個關于字串下標超出范圍的斷言。但在Codecademys的瀏覽器代碼編輯器中,同樣的代碼卻可以運行。 我無法理解為什么它不能在VS中運行。
uj5u.com熱心網友回復:
如果你在除錯模式下運行你的程式(按F5),除錯器將在問題所在的地方停止你的程式。然后你可以檢查你的變數的值,如i和j。
uj5u.com熱心網友回復:
這就是內回圈
for (int j = 0; j < word.size (); j ) {
if (text[i j] == word[j]) {
匹配 。
}
沒有考慮到字串text的尾部可能遠遠小于word.size()的值。所以這個for回圈引發了對字串text以外的記憶體的訪問。
為了避免這種情況,至少要用下面的方式重寫外回圈
。if ( not ( text. size() < word.size() ) )
{
for ( size_t i = 0, n = text. size() - word.size() 1; i < n; i ) {
//...。
更有效和更安全的方法是使用類std::string的方法find而不是回圈。
下面是一個示范程式。
#include <iostream>
#include <string>
std::string & bleep( std::string &text, const std::string &word, char c ) /span>
{
if ( auto n = word.size( ) )
{
for ( std::string:size_type pos = 0;
( pos = text.find( word, pos ) ) != std::string::npos;
pos = n )
{
text.replace( pos, n, n, c ) 。
}
return text;
}
int main()
{
std::string word = "broccoli"。
std::string sentence = "我有時吃西蘭花。"。
std::cout << sentence << '
'。
std::cout << bleep( sentence, word, '*' ) << '
'。
return 0。
程式輸出是
我有時吃西蘭花。
我有時會吃********。
uj5u.com熱心網友回復:
當你在做text[i j]時,當i已經接近句子的末尾時(比如在西蘭花后面的.上),[i j]會超出句子的末尾。
當你在vs的除錯模式下,它將檢查下標的范圍。也許codeacademy的沒有。
你應該增加一個檢查,以確保i沒有超過該詞不能容納在剩余空間的那一點。你可以在這一點上結束外回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/328899.html
標籤:
上一篇:是否有可能使cordova應用在不重新編譯的情況下進行除錯?
下一篇:回圈中的Python圖譜被覆寫了
