簡體   English   中英

在getline()無法執行后進行循環

[英]For Loop after getline() doesn't execute

我可以輸入對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  << '"';
}

打開您的編譯器警告!

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) < sizeof(std::size_t)

std::string::npos定義為std::string::size_type(-1) ,即std::numeric_limits<size_t>::max() ,該值在您的平台上不能用unsigned int表示。

i更改為

std::string::size_type i = 0;

(附帶一提,令人耳目一新的是,您提供了完整的可編譯示例!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM