gpt4 book ai didi

c++ getline函数不允许我输入

转载 作者:行者123 更新时间:2023-11-30 05:46:06 26 4
gpt4 key购买 nike

所以我有一个回文程序,代码如下:

#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());
}

由于某种原因,当我为回文选择 1 时,它不让我写单词,(换句话说,它不让我输入)

控制台只是说:

输入单词、词组、句子:

这个短语是回文!

按键返回菜单

有人知道如何解决这个问题吗?

提前致谢!

最佳答案

当您为回文选择 1 时,您按下回车键。因此,您的输入由数字 1 和换行符组成。你的cin >> selection;读取数字 1,然后是您的 getline(cin, input);读取换行符,将其解释为空行。您没有编写任何代码来对数字后的换行符输入做任何明智的事情,所以没有任何明智的事情发生。

尝试输入 1foof<enter>反而。您的代码会将其读作 1 后跟包含 foof 的行.

关于c++ getline函数不允许我输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29096745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com