cin vs getline()

Our instructor has expressed his preference of getline() over cin in our code, but are there situations where cin would work better.

For example, I'm using a switch...case structure that uses an integer as selector. When prompting the user for an integer why not just use cin to input the integer rather than using getline() and casting the string or char to an integer. Like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 	int option;
        
        cout << "Please enter an integer" << endl;
		
	cin >> option; // accept user's menu option
		
	switch (option)
	{
		case 1:		
			cout << "You chose option 1";
			break;		
		case 2:
			cout << "You chose option 2";
			break;
		case 3:
			cout << "You chose option 3";
			break;
		default:
			cout << "value unknown";
	}
Last edited on
> Our instructor has expressed his preference of getline() over cin in our code,
> but are there situations where cin would work better.

As long as it is expressed as a mere (somewhat personal) preference, and not as a practise that must be blindly followed by everyone ...
Yes, there are many situations where formatted input would work better.

In general, formatted input
1
2
3
4
5
6
7
8
9
10
11
12
 if( std::cin >> value ) 
{
     // do something with the value
}
else
{
     // reject incorrect input
     // inform the user
     // clear the error state
     // discard characters in the input buffer
     // if approprate, retry the input
}

is more appropriate if we expect the input to be strictly formatted and correct, and/or we want to reject incorrect input.

Unformatted input
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 if( std::getline( std::cin, string ) ) 
{
     // parse the string
     if( the parse is successful )
    {
          // do something with the parsed information
    }
    else
    {
          // parse error
          // inform the user
          // if approprate, retry the input
    }
}
     // if approprate, retry the input
}

is more appropriate if we expect the input to be in free format (there are a variety of different ways in which the input could be given), and/or the input could contain embedded white-spaces.

Between the two, formatted input is more fundamental. Even if we perform unformatted input of a number, at some stage we have to resort to some form of formatted input (convert a sequence of characters to a number).

Also between the two, unformatted input is more forgiving of errors in the expected format of the input.

When alternatives are available (formatted / unformatted input, vector / deque / list, struct / tuple, raw pointer / unique_ptr / shared_pointer etc.), use your judgement to pick the one that is most suitable for your purpose. The 'one size fits all' approach typically leads to misfits is some situation or the other.
Topic archived. No new replies allowed.