【问题标题】:For Loop after getline() doesn't executegetline() 后的 For 循环不执行
【发布时间】:2014-12-11 06:31:39
【问题描述】:

我可以输入输入以调用 getline(cin, input, '\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  << '"';
}

【问题讨论】:

  • 简单调试:(1)在循环前打印l中的字符串; (2) 打印i的值,或者i的值会得到:cout &lt;&lt; l.find("cat", 0) &lt;&lt; "\n";

标签: c++ for-loop getline


【解决方案1】:

打开编译器警告!

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_t,在您的平台上定义为sizeof(unsigned int) &lt; sizeof(std::size_t)

std::string::npos 定义为std::string::size_type(-1),即std::numeric_limits&lt;size_t&gt;::max(),在您的平台上无法用unsigned int 表示的值。

i 更改为

std::string::size_type i = 0;

(顺便说一句,您包含了一个完整的、可编译的示例,这令人耳目一新!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2021-08-10
    相关资源
    最近更新 更多