C++在Xcode中暂停

C++ in Xcode pausing

本文关键字:暂停 Xcode C++      更新时间:2023-10-16

这是我的第一篇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循环中得到错误。关于如何使我的程序适用于不同的单词、多种长度的单词,以及如何在文本中突出显示单词,任何其他建议都会很有帮助。如果有人能帮我解决问题,我将不胜感激。谢谢

我在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

您的问题是:在将字符串text用作索引之前,for循环会检查以确保i在其正确的范围内,但随后您也会将i+1i+2i+3用作索引,而不检查这些值是否也有效。

修复该检查,程序看起来运行良好(输入正确)。


一些杂七杂八的评论。

  • 使用更一致的缩进。它使程序更易于阅读和遵循。以下是我将如何缩进它(使用clang格式工具)
  • #define SPACE ' '(char)看起来是个坏主意,即使您没有使用它
  • using namespace std;通常不受欢迎,但只要你不把它放在标题中,它通常不会引起太多麻烦。不过我仍然可以,因为你可能不理解由此产生的错误消息,所以你可能无论如何都想避免它。如果你真的不喜欢到处写std::,那么就使用更有限的应用程序,比如using std::string;using std::cout;
  • 应该避免全局变量,在这里只需将textUserSubmitwordUserSubmit传递给searchWord()即可
  • 实际上不需要确保CCD_ 15的长度小于或等于500个字符。您使用的是std::string,因此它可以容纳更长的输入
  • 您永远不会检查word的长度,即使您的代码要求它至少有4个字符长。幸运的是,您正在使用at()对其进行索引,这样您就不会得到未定义的行为,但您仍然应该进行检查。我会删除textQuery中的复选框,并在wordQuery中添加一个