detecting enter key with vectors

#include <iostream>
#include <iomanip> // let's start using "manipulator" for output formatting!
#include <vector>
using namespace std;

vector<string> split(const string& s)
{
vector<string> ret;
typedef string::size_type string_size;
string_size i = 0;

// invariant: we have processed characters [original value of i, i)
while (i != s.size()) {
// ignore leading blanks
// invariant: characters in range [original i, current i) are all spaces
while (i != s.size() && isspace(s[i]))
++i;

// find end of next word
string_size j = i;
// invariant: none of the characters in range [original j, current j)is a space
while (j != s.size() && !isspace(s[j]))
j++;

// if we found some nonwhitespace characters
if (i != j) {
// copy from s starting at i and taking j - i chars
ret.push_back(s.substr(i, j - i));
i = j;
}
}
return ret;
}

int main() {
string s,str,line; vector<string>v;
int x; int width;
// buffer to read a line.

cout << "Type your paragraphs. Empty return stops reading." << endl << "> ";
while (getline(cin, s)) {

if (s == "") break;

for(unsigned int i =0; i<s.size(); i++){
if (s[i]=='\n'){str+=" ";}else{
str +=s[i];}
}
cout << "> ";
v = split(str);
}


for (vector<string>::size_type i = 0; i < v.size(); ++i)
cout << v[i] <<endl;



if i use ">it is a book"
">book is " for input
i want to get the output as

it
is
a
book
book
is

but it gives the out put as
it
is
a
bookbook
is.

what is wrong with my code?


Last edited on
while (getline(cin, s)) {

std::getline won't append the delimiting character (\n in this case), to s. It will extract it from the stream, but won't append it.

If it did append it as you are expecting, then the test for an empty string (if (s == "") break;) wouldn't work, because there will always be at least a \n in the returned string.
it does work. but i want to know how should i get the last word of the first line and the first word of the next line to be separate in the output???
Last edited on
Topic archived. No new replies allowed.