Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ getline()之后的For循环不执行_C++_For Loop_Getline - Fatal编程技术网

C++ getline()之后的For循环不执行

C++ getline()之后的For循环不执行,c++,for-loop,getline,C++,For Loop,Getline,我可以为getlinecin的调用输入输入,输入“\n”,但它永远不会结束。我可以继续提供意见。我尝试不使用for循环,它接受getline的输入,然后打印它。所以我猜这是for循环的一个问题。我没有编译器错误 #include <iostream> #include <string> using namespace std; int main() { unsigned int i = 0; int cat_appearances = 0; string l

我可以为getlinecin的调用输入输入,输入“\n”,但它永远不会结束。我可以继续提供意见。我尝试不使用for循环,它接受getline的输入,然后打印它。所以我猜这是for循环的一个问题。我没有编译器错误

#include <iostream>
#include <string>
using namespace std;

int main()
{
  unsigned int i = 0;
  int cat_appearances = 0;
  string l;
  cout << "Please enter a line of text: " << endl;
  getline(cin, l, '\n');

  for (i  = l.find("cat", 0); i != string::npos; i = l.find("cat", i)) {
    cat_appearances++;
    //move past the last discovered instance to
    //avoid finding same string again
    i++;
  }

  cout << "The word cat appears " << cat_appearances
       << " in the string " << '"' << l  << '"';
}

打开编译器警告

warning: comparison is always true due to limited range of data type [-Wtype-limits]
         for(i  = l.find( "cat", 0); i != string::npos; i = l.find("cat",i ))
                                       ^
std::string::npos的类型是实现定义的,编译器可能将其定义为std::size\u t,并且在您的平台上sizeofunsigned int std::string::npos定义为std::string::size_type-1,即std::numeric_limits::max,在您的平台上,该值不能用无符号int表示

我改成


另一方面,令人耳目一新的是,您包含了一个完整的、可编译的示例

简单调试:1在循环前用l打印字符串;2打印i的值,或我将得到的值:cout
std::string::size_type i = 0;