#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector <string> words;

void splitSent (string sent);



int main ()
{
string sent;

cout << "Enter your sentence: " << endl;
getline (cin, sent);
splitSent (sent);


string finalSent;
for (unsigned int i = 0; i < words.size(); i++)
 {
    if (words[i] == "i")
    {
        finalSent += "I ";
        i++;
    }

    if (words[i] == "instructor")
    {
        finalSent += "name of prof ";
        i++;
    }

    finalSent += words[i];
    finalSent += " ";
 }

cout << "Final sentence is: " << finalSent << "." << endl;


return 0;
}


void splitSent (string sent)
{
int Pos = 0; // Position
string word;

while (Pos < sent.length())
{
    while ((Pos < sent.length()) && (sent[Pos] != ' '))
    {
        word += sent[Pos];
        Pos++;
        if (sent[Pos] == '.')
         {
            break;
         }
    };
words.push_back(word);
word = "";
Pos++;
}
}


到目前为止,这是我的程序,我正在尝试用“ I”替换“ i”,并用教授的名字替换“ instructor”。但是,每当一个句子中有两个以上的“ i”时,我都会不断收到错误消息,并且不确定为什么。如果我的句子中有单词“ instructor”,我也会收到相同的错误消息

最佳答案

无需手动增加i。顺便说一下,这就是for循环的作用。通过增加i,您将越过向量的大小并明显访问未定义的内存

string finalSent;
    for (unsigned int i = 0; i < words.size(); i++)
    {
        if (words[i] == "i")
        {
            finalSent += "I ";
            continue;
            //i++;
        }

        if (words[i] == "instructor")
        {
            finalSent += "name of prof ";
            continue;
            //i++;
        }

        finalSent += words[i];
        finalSent += " ";
    }

关于c++ - 错误,返回值3221225477,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36416526/

10-11 22:45
查看更多