这是我的第一篇 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 循环中得到错误。关于如何使我的程序适用于不同的单词、多种长度的单词以及如何突出显示文本中的单词的任何其他建议都会有所帮助。 如果有人可以帮助我解决我的问题,我将不胜感激。谢谢!
最佳答案
I get the error at the for loop.
您应该描述您遇到的错误。我碰巧可以访问 Xcode,所以我可以运行你的代码,看看会发生什么,但你应该尽量避免那些你需要帮助的人。
在这种情况下,您应该描述调试器如何在以下行停止程序:
char ch_4 = text.at(i + 3);
包含消息:“Thread 1: signal SIGABRT”并且控制台输出显示
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
你的问题是这样的:for
循环检查以确保 i
在使用它之前在字符串 text
的正确范围内作为索引,但随后您还可以使用 i+1
、i+2
和 i+3
作为索引,而无需检查这些值是否也有效。
修复该检查,程序似乎运行良好(给定正确的输入)。
一些杂七杂八的评论。
- 使用更一致的缩进。它使程序更易于阅读和遵循。 Here's我将如何缩进它(使用工具 clang-format )。
#define SPACE ' '(char)
看起来是个坏主意,即使您没有使用它也是如此。using namespace std;
通常不受欢迎,但只要您不将它放在 header 中,它通常不会造成太多麻烦。不过我仍然可以,因为您可能不会理解由此产生的错误消息,所以您可能还是想避免它。如果你真的不喜欢到处写std::
那么使用更有限的应用程序,例如using std::string;
和using std::cout;
。- 应避免使用全局变量,您只需将
textUserSubmit
和wordUserSubmit
传递给searchWord()
即可。 - 确实没有必要确保
text
的长度小于或等于 500 个字符。您正在使用std::string
,因此它可以容纳更长的输入。 - 您永远不会检查
word
有多长,即使您的代码要求它至少有 4 个字符长。幸运的是,您正在使用at()
对其进行索引,因此不会出现未定义的行为,但您仍然应该检查一下。我将删除textQuery
中的检查并添加一个到wordQuery
。
关于Xcode 中的 C++ 暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23178755/