这是我的第一篇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