打印句子 C++ 的短语时的错误

bug in printing phrases of a sentence c++

本文关键字:错误 短语 打印 C++ 句子      更新时间:2023-10-16
vector <string> oneWordPhrase;
vector <string> twoWordPhrase;
vector <string> threeWordPhrase;    
string str="hello my is bob oh hey jay oh";
vector<string>::iterator it1;
vector<string>::iterator it2;

我将str中的句子分解成单独的单词,并将它们存储到称为oneWordPhrase的向量中。因此,向量的大小为 7

for(it1=oneWordPhrase.begin(); it1!=oneWordPhrase.end(); it1++)
{
    if(it1+1 == oneWordPhrase.end())
        break;  /* if we reach the last element of the vector
                     get out of loop because we reached the end */
    twoWordPhrase.push_back(*it1 + ' ' + *(it1+1));
}//gets each 2 consecutive words in the sentence
cout<<"two word---------------n";
for(int i=0; i<twoWordPhrase.size(); i++)
    cout<<twoWordPhrase[i]<<endl;

这将产生正确的输出:

你好我的

我的是

是鲍勃

鲍勃·

哦 嘿

嘿杰伊

周杰伦哦

for(int i=0; i<twoWordPhrase.size()-1; i++)
{   
    it1=twoWordPhrase.begin()+i;
    it2=oneWordPhrase.begin()+i+2;
    if(it1==twoWordPhrase.end()-1)
        break; //signal break but doesnt work
    threeWordPhrase.push_back(*it1 + ' ' + *it2);
}
cout<<"three words-----------n";
for(int i=0; i<threeWordPhrase; i++)
    cout<<threeWordPhrase[i]<<endl;

这将产生正确的输出,但末尾有两行空白

你好我的是

我的是鲍勃

是鲍勃哦

鲍勃哦嘿

哦嘿杰伊

//空白

//空白

我还尝试在我的 for 循环中使用迭代器来发出中断信号,但它不起作用。为什么要打印两行额外的空白?

为了回答最初的问题,发布的代码是正确的。正如约瑟夫·曼斯菲尔德所怀疑的那样,显示代码(未发布)中存在错误,如此处所示。

在对风格和最佳实践的评论之后,我认为以下是更惯用C++:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
using namespace std;
typedef vector<string> strings;
int main() {
    string s = "one two three four five";
    /* stringstream is a stream just like std::cout
       but reads/writes from/to a string
       instead of the standard input/output */
    stringstream ss(s);
    /* std::vector has a 2 argument constructor
       which fills the vector with all elements between two iterators
       istream_iterator iterates throuw the stream as if
       using operator>> so it reads word by word */
    strings words = 
        strings(istream_iterator<string>(ss), istream_iterator<string>());
    strings threeWords;
    for(size_t i = 0; i < words.size()-2; ++i)
        threeWords.push_back(words[i] + ' ' + words[i+1] + ' ' + words[i+2]);
    for(size_t i = 0; i < threeWords.size(); ++i)
        cout << i << ": " << threeWords[i] << endl;
    return 0;
}

单词拆分代码的灵感来自这篇文章