为什么这个C++程序适用于第一行输入,而不适用于第二行或第三行

why does this C++ program works for the first line of input but not second or third?

本文关键字:适用于 不适用 二行 三行 输入 C++ 一行 为什么 程序      更新时间:2023-10-16

我想写一个程序,如果给定字符串包含">NOT"或">NOT",则打印Real Fancy,如果不包含,则打印Real Fancy。

例如:"这不是字符串"o/p:Real Fancy

"这没什么"o/p:经常幻想

问题是,如果我的第一个测试用例输入是">而不是是此行",它就会打印出Real Fancy。但如果在第二个或更高的测试用例中给出了相同的行作为输入,那么它就不起作用,并且会定期打印。为什么?有什么帮助吗?

这是代码:

#include <bits/stdc++.h>

using namespace std;
int main()
{
int t;//No.of test cases
cin>>t;
while(t--)
{
string quote;//the input from user
string found="not";//word to be found
string temp="";
int not_found=0;
cin.ignore();
getline(cin,quote);
//Splitting the given line into words and store in a vector
vector<string> words;
istringstream iss(quote);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(words));
//Scan for "not" and if found break from for loop
for(int i=0;i<words.size();i++)
{
temp=words[i];
transform(temp.begin(),temp.end(),temp.begin(),::tolower);
if(temp==found)
{
cout<<"Real Fancy"<<endl;
not_found=1;
break;
}
}
if(not_found==0)
cout<<"regularly fancy"<<endl;
}
return 0;
}

输入模式看起来像

t
quote
quote
quote
...

t的读取

cin>>t;

一旦发现不可能是整数的输入,就会停止。这包括表示行结束的换行符,留下流中的换行符供以后使用(请参阅为什么std::getline()在格式化提取后跳过输入?有关该问题的更多信息)。跳过问题已通过解决

cin.ignore();
getline(cin,quote);

while循环中,但这用一个bug换了另一个bug。如果之前没有格式化的输入在流中留下不需要的字符,cin.ignore();将抛出输入的合法第一个字符。

这将发生在第二次和随后的读取中。输入最终看起来像

t //newline consumed by ignore
quote //newline consumed by getline. ignore consumes first character of next line
uote //newline consumed by getline. ignore consumes first character of next line
uote //newline consumed by getline. ignore consumes first character of next line
..

解决方案:

将其移动到流中留下不需要的字符的输入之后

cin>>t;
cin.ignore();

一个更好的替代方案是ignore,这样您就可以确保清除行末尾的所有潜在垃圾

cin>>t;
cin.ignore(numeric_limits<streamsize>::max(), 'n');

这将从流中读取到流的最大可能长度,或者找到并丢弃换行符,以先到者为准。

一定要在一次手术后而不是在下一次手术前进行清理。它使相关代码更紧密地结合在一起,有助于提高可读性,并保护您免受以前没有任何内容需要清理的情况的影响。

相关文章: