2014-04-20 36 views
0

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

+0

欢迎!您可能希望将循环'while(text.size()> 500)'更改为具有缓冲区变量的if语句,一旦用户达到500个字符,while循环将无限循环。 – ultifinitus

+0

@ultifinitus不,他的节目的那部分工作。循环通过询问新的输入来确保输入是“有效的”,直到他想要的大小(小于或等于500个字符长)。 – bames53

+0

@ bames53嘿,你是对的!出于某种原因,我认为他正在用他的循环附加文本,只是不理睬我心不在焉! – ultifinitus

回答

1

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

你的问题是这样的:for循环检查,以确保i是在字符串text正确的范围内,然后用它作为in dex,但您也可以使用i+1i+2i+3作为索引,而不检查这些值是否也有效。

修复检查和程序似乎运行正常(给出正确的输入)。


一些其他的评论。

  • 使用更一致的缩进。它使程序更易于阅读和遵循。 Here's我会如何缩进(使用工具clang-format)。
  • #define SPACE ' '(char)看起来像一个坏主意,即使你不使用它。
  • using namespace std;通常是皱起了眉头,虽然只要你不把它放在头上,它通常不会造成太大的麻烦。我仍然可以,因为你可能不会理解你可能想避免的错误信息。如果你真的不喜欢在任何地方写std::然后使用更多有限的应用程序,如using std::string;using std::cout;
  • 应避免使用全局变量,只需将textUserSubmitwordUserSubmit传递到searchWord()即可。
  • 确实没有必要确定text长度小于或等于500个字符。您正在使用std::string,因此它可以保存更长的输入。
  • 即使您的代码要求它至少有4个字符长,您也不会检查word多长时间。幸运的是,你使用at()来索引它,所以你不会得到未定义的行为,但你仍应该检查。我将删除textQuery中的支票并将其添加到wordQuery
+0

Thankyou回答我的问题!我还是很新的,我不太清楚修复是什么;你能够提交更改后的代码吗? – user3553239

+0

@ user3553239您在for循环中的检查是'i bames53

+0

我应该检查我+ 3.非常感谢你!真的很有帮助。 – user3553239