程序抛出异常

时间:2015-01-13 19:17:20

标签: c++

我正在编写一个程序,允许用户输入一个句子,然后将其存储在一个字符串中,然后程序将删除句子中的任何句号,然后在输出之前创建字符串中每个单词的列表列表到控制台。

只要句子中只有一个完整的句点,程序就能正常运行,但是如果还有更多,它会抛出这个例外:

Project6.exe中0x7696B727处的未处理异常:Microsoft C ++异常:内存位置0x0022F8B8处的std :: out_of_range。

然后如果我继续运行它会抛出:

运行时检查失败#0 - ESP的值未在函数调用中正确保存。这通常是调用使用一个调用约定声明的函数的结果,函数指针使用不同的调用约定声明。

有什么建议吗? (并且在任何人问之前,我知道你通常只会在句子中有一个句号,但我需要在测试中使用超过1个。

这是代码:

 #include <iostream>
 #include <string>

 using namespace std

 string sSentence; // sets up a string variable called sSentence

 int i = 0;

 void RemoveFullStop()
 {
    while(sSentence.find (".") != string::npos) // the program runs this loop until it cannot            find any more full stops in the string
{
        i = sSentence.find("." , i); // find the next full stop in the string and get the      character count of the space and place it in the variable i
        sSentence.replace(i,1,""); // remove the full stop
    }
}

void ListWords()
{
    while(sSentence.find (" ") != string::npos) // the program runs this loop until it cannot find any more spaces in the string
    {
        i = sSentence.find(" " , i); // find the next space in the string and get the character count of the space and place it in the variable i

        // cout << i << endl; // output the contents of iWordSpace to the console (used for debugging - no longer used)

        sSentence.replace(i,1,"\n");

        // cout << sSentence << endl; // output the contents of iWordSpace to the console (used for debugging - no longer used)

        }
    }

   int main()
   {
        getline(cin, sSentence); // get user input and store it in sSentence (using the getline     function so the .find operation works correctly)

        RemoveFullStop(); // calls the RemoveFullStop void function that removes all full stops from the string

        ListWords(); // calls the ListWords void function that splits the string into a list of words

        cout << endl; // formatting line
        cout << "The words that were in the sentence were:" << endl;
        cout << endl; // formatting line
        cout << sSentence << endl;
        cout << endl; // formatting line

    system("pause");

    return 0;
}

2 个答案:

答案 0 :(得分:0)

问题是您在iRemoveFullStop中继续使用ListWords

i只会增加,所以最终它可以越过字符串的结尾。

你真的不需要全局i变量来完成这项任务。

答案 1 :(得分:0)

发生这种情况的原因是,当ListWords中的sSentence.find(" " , i)运行时,我的值不为0,因为它已在RemoveFullStop()中定义。要解决此问题,请先删除int i = 0;,然后将其添加到RemoveFullStop()ListWords() 此外,虽然这只是一种风格,并且不会影响您的代码运行能力,但我不会将此变量i称为i,j,k通常意味着计数器。将此变量称为更恰当描述性的内容。

这是应该的相关代码。

 using namespace std
 string sSentence; 

void RemoveFullStop()
{
    int charPlace = 0;
    while(sSentence.find (".") != string::npos) 
    {
        charPlace = sSentence.find("." , charPlace); 
        sSentence.replace(charPlace,1,""); 
    }
}

void ListWords()
{
    int charPlace = 0;
    while(sSentence.find (" ") != string::npos) 
    {
        charPlace = sSentence.find(" " , charPlace);
        sSentence.replace(charPlace,1,"\n");
    }
}