cin is giving me an infinite loop

Hello, super new c++ programmer here. I am trying to make a program that allows uses to input movies and then format them to a list. However when a user inputs more than one word my program goes into an infinite loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	int option = ' ';
	string addMovie;
	vector<string> movies;
	vector<string>::iterator iter;
	while (option != 'q')
	{
	string menu = "movie and game list\n 1) Add a movie \n 2) list all movies \n 3) sort all movies\n";
	cout << menu;
		cin >> option;

		if (option == 1)
		{	
			cout << "\nPlease type in your movie: ";
			cin >>addMovie;
			movies.push_back(addMovie);
			cout << endl;
		}
Look what happens if you emter "Awesome movie":

Input buffer: "Awesome movie\n" cin >>addMovie; reads Awesome
Input buffer: " movie\n" cin >> option; tries to read int, fails when encounters letter m and sets stream in failed state. That means all further reads will fail too untill error state is cleared. option is unchanged. SO it enters into movie add branch, read fails (because of stream state) addMovie is unchanged, cin >> option; executes, fails, etc...

Use getline() to read whole line: http://en.cppreference.com/w/cpp/string/basic_string/getline

Answering your next problem: http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction
The extraction operator stops processing the string when it encounters a whitespace character. So if your user tries to add something like "This is my movie" only "This" would be added to the string leaving the rest of the entry in the input buffer. If the next operation is an extraction to a numeric variable the stream will fail because you can't enter a character into a numeric variable. You should consider using getline() instead of the extraction operator.

And note your while() clause will probably not do what you expect, remember option is an int not a char.

Ahh I see now, I figured it had something to do with the cin value. So far we have only been developing very basic applications without things like error catching etc. Anyway thank you for the help
Topic archived. No new replies allowed.