input output string type does not work in switch case statement

Hello all, please help solve this..i cannot make an input and output inside the switch cases statement.when i put the input output string type out of the switch case statement, it worked.

#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
char choice;

cout << "Demo Switch Case + input string\n\n";
cout << "Please enter 1 to continue\n";
cin >> choice;
switch (choice)
{
case '1':
{
cout << "Please enter a string: \n\n";
getline(cin, str);
cout << str;
break;
}
default:
{
cout << "Invalid input\n\n";
break;
}
}
return 0;
}
Last edited on
1
2
3
4
5
char choice[1];
cout<<"Demo Switch Case + input string\n\n";
cout<<"Please enter 1 to continue\n";

switch(choice[0])

So where exactly does choice[0] acquire a value that you typed in?

> defaut:
Switch statements will do odd things if you can't spell 'default' properly.
Sorry, the post have some typo...i edit already...Please help
Last edited on
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
#include <iostream>
#include <string>

int main()
{
    char choice;

    std::cout << "Demo Switch Case + input string\n\n"
              << "Please enter 1 to continue: ";
    std::cin >> choice;

    switch(choice)
    {
        case '1':
        {
            std::string str ;
            std::cout << "Please enter a string: ";

            // extract and discard the new line remaining in the input buffer
            // more info: http://www.cplusplus.com/forum/general/63681/#msg344674
            std::cin >> std::ws ;

            std::getline( std::cin, str ) ;
            std::cout << str << '\n' ;
            break;
        }

        default:
            std::cout << "Invalid input\n\n";
    }
}
Thank you
Topic archived. No new replies allowed.