#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”,我会不断收到错误信息,我不知道为什么。如果我的句子中有“讲师”一词,我也会得到同样的错误信息
答案 0 :(得分:1)
无需手动增加id
。这就是i
循环所做的事情。通过递增for
,您将超出向量的大小,并明显访问未定义的内存
i
答案 1 :(得分:0)
正如Obicere在评论中提到的那样,您可能会遇到细分错误,因为您手动递增i
,然后要求words[i]
。你可能只是在&#34; i&#34;或&#34;讲师&#34;在句子结束时,变量i
已经达到应有的高度。但是你做了i++
,所以i
比它应该更大,words[i]
要求words
的元素超过它的结尾。这就是段错误的发生方式。
你应该对你的if
陈述以及之后发生的事情更加谨慎。顺便说一句,使用全局变量是个坏主意。在这种情况下,您不应该在文件顶部定义words
,但您应该通过引用传递它。另外,一个好的编辑器(emacs或vim)可以让你的代码更加整洁。
我不完全确定你想要什么,所以我可能搞乱了流控制,但这段代码应该更接近你想要的。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void splitSent (string sent, vector<string>& words);
int main () {
string sent;
vector<string> words;
cout << "Enter your sentence: " << endl;
getline(cin, sent);
splitSent(sent, words);
string finalSent;
for (unsigned int i = 0; i<words.size(); i++) {
if (words[i] == "i") {
finalSent += "I";
} else if (words[i] == "instructor") {
finalSent += "name of prof";
} else {
finalSent += words[i];
}
if (i<words.size()-1) { // Don't put a space before the period
finalSent += " ";
}
}
finalSent += ".";
cout << "Final sentence is: " << finalSent << endl;
return 0;
}
void splitSent (string sent, vector<string>& words) {
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++;
}
}