【发布时间】:2014-04-20 05:23:53
【问题描述】:
这是我的第一个 SO 帖子。 我对编程很陌生,使用 C++ 我想我可以尝试制作一个程序,允许用户提交一个文本块(最多 500 个字符),允许他们输入一个 4 个字母的单词,程序返回金额有时它会在文本中选择该词。 我正在使用 X 代码,它不断创建一个绿色断点并在“for”循环函数处暂停程序。我的代码如下所示:
#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 不,他的程序的那一部分有效。该循环只是通过要求新输入直到达到他想要的大小(小于或等于 500 个字符长)来确保输入是“有效的”。
-
@bames53 嘿,你是对的!出于某种原因,我认为他在循环中附加文本,请忽略我心不在焉!
-
@bames53 我在 bames53 的帮助下修复了程序。我现在只需要弄清楚如何没有字数限制(即单词不必是 4 个字母长)并且它仍然可以工作。有什么建议么?顺便说一句,我做了建议的更改。
-
@user3553239 您不需要
ch_1、ch_2等变量。您可以直接比较text.at(i + 2) == word.at(2)等。然后您应该能够弄清楚如何编写一个内部循环,其中您当前有if检查检查单词中的每个字符与text中的正确字符。
标签: c++ xcode breakpoints