打印句子 C++ 的短语时的错误
bug in printing phrases of a sentence c++
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;
}
单词拆分代码的灵感来自这篇文章
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 打印句子 C++ 的短语时的错误