How do I use getline with switch statement?

I have a problem with the switch statement because it doesn't prompt me to input something.

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
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
#include<cstring>
using namespace std;
//Compiler: Dev C++ and cygwin

void rd()
{
  string txt;
  ofstream output_file;
  output_file.open( "example.txt" );
  cout<<"Please type the word Hello world : ";
  getline(cin,txt);
  cout<<txt<<" was written in the example.txt file"<<endl;
  output_file << txt;
  output_file.close();
}

int main()
{
	int choice;
	while(true)
	{
		cin>>choice;

		switch(choice)
		{
			case 1:
				rd();
				break;
			default:
				cout<<"Invalid choice";
	        }
        }				
    rd();
}


I want to get rid of this kind of output
Please type the word Hello world :  was written in the example.txt file
Last edited on
The issue has nothing to do with the switch statement. The issue is that on line 24 you take input but then leave the newline character for the next guy to deal with. You can ingore() it so that it goes away.

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

See also keskiverto's post below.
Last edited on
http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction
0x499602D2 wrote:
If you are mixing formatted input with unformatted input and you need to discard residual whitespace, use std::ws. Otherwise, if you need to clear out invalid input regardless of what it is, use ignore().
You need to ignore "cin.ignore() " the end of line from previous feed.
Your rd function should be as below. This is working.

void rd()
{
string txt;
ofstream output_file;
output_file.open( "example.txt" );
cout<<"Please type the word Hello world : ";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
std::getline(std::cin,txt);
cout<<txt<<" was written in the example.txt file"<<endl;
output_file << txt;
output_file.close();
}
A pet peeve of mine is that line 14 happens before line 15 - that's like telling your mom you did your homework and only then going to start work on it.
Last edited on
lisura pud sabton ana uie.
Topic archived. No new replies allowed.