So I'm writing this code that takes a phrase and translates it into Pig Latin and will do that until the user decides to stop. Im using a switch statement for the choice between (T) for translate and (Q) for quit. My default and (Q) switches work great, but when I use my (T) option it just prints out the cout line then goes back to the menu. Any ideas why or how to fix?
#include<iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
usingnamespace std;
// Prototype for the function
void printLatinWord(char *);
int main()
{
// Declare variables
char phrase[20];
char *token = NULL;
char *token2 = NULL;
char option;
while (1)
{
fflush(stdin); // Used to clear input
cout << "Luke's Pig Latin Translator\nPress (T) to translate a phrase into piglatin.\nPress (Q) to quit.\nChoice: ";
cin >> option;
switch (option)
{
case'T':
// Prompt the user for input
cout << "Enter a phrase to be translated into piglatin: ";
// Read the input from the user
cin.getline(phrase, 200);
// Extract the first token
token = strtok_s(phrase, " ", &token2);
// While there are tokens in "string"
while (token != NULL)
{
// Call the print latin word function
printLatinWord(token);
// Insert a blank according to the phrase
cout << " ";
// Get the next token
token = strtok_s(NULL, " ", &token2);
}
cout << endl;
break;
case'Q':
cout << "Thank you! Now quitting..." << endl;
system("pause");
exit(1);
default:
cout << "That is not a valid option. Please enter either (T) or (Q)" << endl;
break;
}
}
return 0;
}
// Prints the pig latin word
void printLatinWord(char *letter)
{
// sepearate the first letter
char firstletter = *letter;
// print the rest of the word, then the first letter, then ay
cout << ++letter << firstletter << "ay";
}
> char phrase[20];
...
> cin.getline(phrase, 200);
Lying about your buffer sizes won't do you any good.
> fflush(stdin); // Used to clear input
a) mixing C and C++ is bad
b) fflush() isn't defined for input streams anyway. Don't expect this to work wherever you go.
You need to call ignore on cin. When you did cin >> option, the char was consumed, but the new line character was left. When you called cin.getline(), you consumed the new line character. The ignore function (look it up) will clean out the new line character for you.