2014-04-20 35 views
0

這是我的第一篇SO帖子。 我對編程非常陌生,並且用C++編寫,我想我可能會嘗試製作一個允許用戶提交一個文本塊(最多500個字符)的程序,允許他們輸入一個4個字母的單詞,程序返回它在文本中選擇該單詞的次數。 我正在使用X代碼,並且它不斷製作綠色斷點並在'for'循環函數中暫停程序。我的代碼如下所示:Xcode中的C++暫停

#include <iostream> 
#include <string> 
#include <math.h> 
#define SPACE ' '(char) 
using namespace std; 

//Submit text (maximum 500 characters) and store in variable 
string text; 
string textQuery(string msgText) { 
do { 
cout << msgText << endl; 
    getline(cin, text); } while (text.size() > 500); 
return text; 
} 
//Query word to search for and store as variable 
string word; 
string wordQuery(string msgWord) { 

cout << msgWord << endl; 
cin >> word; 
return word; 
} 
//Using loop, run through the text to identify the word 
int counter = 0; 
bool debugCheck = false; 
int searchWord() { 

for (int i = 0; i < text.size(); i++) { 
    char ch_1 = text.at(i); 
    char ch_2 = text.at(i + 1); 
    char ch_3 = text.at(i + 2); 
    char ch_4 = text.at(i + 3); 
    cout << i; 

    if(ch_1 == word.at(0) && 
     ch_2 == word.at(1) && 
     ch_3 == word.at(2) && 
     ch_4 == word.at(3)) 
    { 

     counter++; 
     debugCheck = true; 

    } 


} 

return counter; 
} 
//cout the result 
int main() { 
string textUserSubmit = textQuery("Please submit text (max 500 characters): "); 
string wordUserSubmit = wordQuery("Please select a word to search for: "); 
int counterResponse = searchWord(); 
cout << debugCheck << endl; 
cout << "The number of times is: " << counterResponse << endl; 
return 0; 
} 

我在for循環中得到錯誤。關於如何讓我的程序適用於不同的單詞,多個詞的長度以及如何突出顯示文字中的單詞的任何其他建議將會有所幫助。 如果有人能幫我解決我的問題,我真的很感激。謝謝!

+0

歡迎!您可能希望將循環'while(text.size()> 500)'更改爲具有緩衝區變量的if語句,一旦用戶達到500個字符,while循環將無限循環。 – ultifinitus

+0

@ultifinitus不,他的節目的那部分工作。循環通過詢問新的輸入來確保輸入是「有效的」,直到他想要的大小(小於或等於500個字符長)。 – bames53

+0

@ bames53嘿,你是對的!出於某種原因,我認爲他正在用他的循環附加文本,只是不理睬我心不在焉! – ultifinitus

回答

1

我在for循環中得到錯誤。

你應該描述你得到的錯誤。我恰好有權訪問Xcode,所以我可以運行你的代碼,看看會發生什麼,但是你應該儘量避免你需要幫助的人。

在這種情況下,應該描述調試器在線路如何停止該程序:

char ch_4 = text.at(i + 3); 

包括消息:「線程1:信號SIGABRT」和控制檯輸出顯示

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string 

你的問題是這樣的:for循環檢查,以確保i是在字符串text正確的範圍內,然後用它作爲in dex,但您也可以使用i+1i+2i+3作爲索引,而不檢查這些值是否也有效。

修復檢查和程序似乎運行正常(給出正確的輸入)。


一些其他的評論。

  • 使用更一致的縮進。它使程序更易於閱讀和遵循。 Here's我會如何縮進(使用工具clang-format)。
  • #define SPACE ' '(char)看起來像一個壞主意,即使你不使用它。
  • using namespace std;通常是皺起了眉頭,雖然只要你不把它放在頭上,它通常不會造成太大的麻煩。我仍然可以,因爲你可能不會理解你可能想避免的錯誤信息。如果你真的不喜歡在任何地方寫std::然後使用更多有限的應用程序,如using std::string;using std::cout;
  • 應避免使用全局變量,只需將textUserSubmitwordUserSubmit傳遞到searchWord()即可。
  • 確實沒有必要確定text長度小於或等於500個字符。您正在使用std::string,因此它可以保存更長的輸入。
  • 即使您的代碼要求它至少有4個字符長,您也不會檢查word多長時間。幸運的是,你使用at()來索引它,所以你不會得到未定義的行爲,但你仍應該檢查。我將刪除textQuery中的支票並將其添加到wordQuery
+0

Thankyou回答我的問題!我還是很新的,我不太清楚修復是什麼;你能夠提交更改後的代碼嗎? – user3553239

+0

@ user3553239您在for循環中的檢查是'i bames53

+0

我應該檢查我+ 3.非常感謝你!真的很有幫助。 – user3553239