为什么这个C++程序适用于第一行输入,而不适用于第二行或第三行
why does this C++ program works for the first line of input but not second or third?
我想写一个程序,如果给定字符串包含">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');
这将从流中读取到流的最大可能长度,或者找到并丢弃换行符,以先到者为准。
一定要在一次手术后而不是在下一次手术前进行清理。它使相关代码更紧密地结合在一起,有助于提高可读性,并保护您免受以前没有任何内容需要清理的情况的影响。
相关文章:
- OpenGL - 在 NDC 中计算位置适用于着色器,但不适用于'regular'程序
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 如何修复我的最大公约数代码?它适用于除零和零以外的所有数字
- 选择排序C++(已修改)并非适用于所有情况
- 无法让"std::enable_if"适用于无作用域枚举
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 确定夏令时是否适用于特定日期
- 是否有一种 STL 算法可以最后找到,但它也适用于指针?
- 十进制到二进制的实现不能完全适用于我大学的检查器。问题或提示可能是什么
- 使用程序集嵌入数据时"Undefined reference"错误,使用适用于窗口的 mingw-w64 编译(COFF 而不是 ELF)
- 为什么 std::vector 适用于类定义中的不完整类型?
- 为什么哈希<常量字符*>适用于字符串而不是字符串变量?
- Lambda适用于最新的Visual Studio,但在其他地方不起作用
- 我该如何文档文档以使文档适用于类成员而不是匿名类型
- 计算 c# 中二进制文件符号的频率不起作用,但适用于等效的 c++ 代码
- 为什么 fstream.open(文件名) 适用于文字而不是生成的字符串?
- 模板重载和 SFINAE 仅适用于函数而不是类
- 为什么链接器不抱怨多个函数定义(仅适用于模板化函数)
- 我可以使用' == '来比较两个向量吗?我试过了,似乎工作正常。但我不知道它是否适用于更复杂的情况
- 延长临时的生命周期,适用于块范围的聚合,但不是通过"新";为什么?