這是我的第一篇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循環中得到錯誤。關於如何讓我的程序適用於不同的單詞,多個詞的長度以及如何突出顯示文字中的單詞的任何其他建議將會有所幫助。 如果有人能幫我解決我的問題,我真的很感激。謝謝!
歡迎!您可能希望將循環'while(text.size()> 500)'更改爲具有緩衝區變量的if語句,一旦用戶達到500個字符,while循環將無限循環。 – ultifinitus
@ultifinitus不,他的節目的那部分工作。循環通過詢問新的輸入來確保輸入是「有效的」,直到他想要的大小(小於或等於500個字符長)。 – bames53
@ bames53嘿,你是對的!出於某種原因,我認爲他正在用他的循環附加文本,只是不理睬我心不在焉! – ultifinitus