简体   繁体   中英

c++ getline function does not let me input

So i have a palindrome program and here are the codes:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

void palindrome();
void compareTwoInt();
bool validation(const string&);

int main()
{
int selection;
cout << "\t\t\t MENU\n";     
cout << "\t\t\t ----\n";
cout << "\t\t\t1. Palindrome";
cout << "\n\t\t\t2. Compare Two Integers";
cout << "\n\t\t\t3. End program\n";
cout << "\n\t\t\tEnter your choice : ";
cin >> selection;

while (selection < 0 || selection > 4)
{
    cout << "\t\t\nInvalid entry. Please enter an appropriate entry.";
    cout << "\n\n \t\t\tEnter your choice: ";
    cin >> selection;
}
if (selection == 1)
{
    cout << "Enter a word, phrase, sentence: \n";
    string input;
    getline(cin, input);

    string input2;
    for (unsigned int i = 0; i < input.length(); i++)
    {
        if (isalnum(input[i]))
        {
            input2 += toupper(input[i]);
        }
    }

    cout << input2 << endl;

    if (validation(input2))
    {
        cout << "The phrase is a palindrome!" << endl;
        cout << "Press <Enter> key back to menu" << endl;

    }

    else
    {
        cout << "The phrase is not a palindrome!" << endl;
        cout << "Press <Enter> key back to menu" << endl;

    }
    fflush(stdin);
    cin.get();
    system("cls");
    return main();

}
else if (selection == 2)
{
    compareTwoInt();
    fflush(stdin);
    system("cls");
    return main();
}
else if (selection == 3)
{
    cout << "\t\t Good Bye. Press <Enter> key to End the program.\n";


}
fflush(stdin);
cin.get();
return 0;
}



void compareTwoInt()
{
int first, second;
cout << "\n\nEnter your positive integer : ";
cin >> first;
cout << "\nEnter your positive integer : ";
cin >> second;


fflush(stdin);
cin.get();


}

bool validation(const string& input)
{
    return input == string(input.rbegin(), input.rend());
}

for some reason when i choose 1 for the palindrome, it doesn't let me write the words, (in another words, it doesn't let me input)

the console just says:

Enter a word, phrase, sentence:

The phrase is palindrome!

Press key back to menu

Anybody have an idea how to fix this?

Thanks in advance!

When you choose 1 for the palindrome, you hit enter. Thus your input consists of the number 1 followed by a newline. Your cin >> selection; reads the number 1 and then your getline(cin, input); reads the newline, which it interprets as an empty line. You have written no code to do anything sensible with the newline character input after the number, so nothing sensible happens.

Try typing 1foof<enter> instead. Your code will read that as a 1 followed by a line containing foof .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM