繁体   English   中英

为什么此C ++程序适用于输入的第一行而不适用于第二行或第三行?

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

我想编写一个程序,如果给定的字符串包含“ NOT ”或“ not ”,则打印Real Fancy,如果不包含,则定期打印。

例如:“这不是字符串” o / p:真实的幻想

o / p:“这没什么”:定期看中

问题是,如果我的第一个测试用例输入是“ not is this line”,它将打印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循环中,但这将一个错误换成了另一个。 如果没有先前格式化的输入以将不需要的字符留在流中,则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');

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

一定要在手术后而不是下一次清理。 它将相关的代码保持在一起,以提高可读性,并保护您免于清理前的麻烦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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