The problem in this is that the program accepts a string with spaces only for the first input and not for the rest of the inputs. It seems that getline only works for the first input.
How can you make the vector store string with spaces (as elements of the vector)?
Enter string:Harry Potter
Enter string:
Anymore(y/n):y //The cursor comes here directly when y is input
Enter string:
Anymore(y/n):Superman //When you try to enter a string
//The program abruptly ends

using namespace std;
int main()
    string n;
    vector<string> a;
    char ch='y';
    vector<string>::iterator i;
                           cout<<"\nEnter string:";
    return 1;

Recommended Answers

All 2 Replies

When mixing getline() and >> in the same program you have to account for the fact that >> leaves the terminating whitespace (new line char usually) in the input buffer. Then when getline() comes around after a call to >> it finds the terminating char to the previous >>, newline, which is it's default terminating char, so it doesn't enter anything into the variables desired.

1) Never mix getline() and other input methods that leave terminating whitespaces in the input buffer, like >>.
2) In programs where you do mix getline() and other input methods that leave terminating whitespace chars then be sure you clear the input buffer to be(as sure as possible) getline() does what you want it to do. The level of sophistication you might want to get here varies on how sophisticated you want to be. A simple call to the istream ignore() method, ignoring just a single leading whitespace char in the input buffer will do for many straightforward programs. Ignoring up to 1080 char is a little more sophisticated. Ignoring up to the maximum size of he input buffer is the most rigorous solution I've seen.

Thank You very much.
Your reply helped me in solving my problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.