输出 Befor 给出字符串的输入以查找回文

Output Befor giving the input of string for finding palindrome

本文关键字:输入 查找 回文 字符串 Befor 输出      更新时间:2023-10-16

此代码在输入测试用例的值后立即给出输出 YES。 代码:用于字母数字回文

int main() {
int t;
cin>>t;
while(t--){
string s;
int count = 0,size = 0;
getline(cin,s);
cout<<s<<endl;
s.erase(remove_if(s.begin(),s.end(),not1(ptr_fun((int(*)(int))isalnum))), s.end());
for(int i=0;i<=s.size()/2;i++){
size++;
if(tolower(s[i])==tolower(s[s.size()-i-1])){
count++;
}
else
break;
}
if (count==size)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}

我得到的输出是 YES,没有给出任何字符串输入

For Input:
2
I am :IronnorI Ma, i
Ab?/Ba
Your Output is:
YES
I am :IronnorI Ma, i
YES

此代码在输入测试值后给出输出 YES 箱。我得到的输出是 YES,没有给出任何字符串输入

您的问题就在这里:

/* code */
cin>>t;    -----------> std::cin        
while(t--)
{
string s;
int count = 0,size = 0;
getline(cin,s); ------------> std::getline()
/* remaining code */

使用类似std::cin的内容进行读取会在输入流中保留换行符。当控制流达到std::getline()时,换行符将被丢弃,但输入将立即停止。这会导致std::getline()尝试读取新行并跳过输入。

FIX:从空格分隔的输入切换到换行分隔的输入时,您希望通过执行std::cin.ignore()来清除输入流中的所有换行

符固定代码应为:https://www.ideone.com/ucDa7i#stdin

#include <iostream>
#include <string>
#include <limits>
#include <algorithm>
int main()
{
int t;
std::cin >> t;
// fix
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
while(t--)
{
std::string s;
int count = 0,size = 0;
getline(std::cin,s);
/* remaining code */
}