2012-04-17 39 views
-1

這裏是短代碼片段,如果在給定的字符串中的任何空間哪個錯誤在下面的代碼中?

#include<string> 
#include<iostream> 
#include<cctype> 
using namespace std; 
//performs string operations 
void string_get() 
{ 
    string text; 
    cout<<" enter string "<<endl; 
    getline(cin,text); 
    string::size_type position=text.find(' '); 
    if(position!=string::npos) 
    { 
     if(text.find(' ',position+1)!=string::npos) 
     { 
      cout<<" contains at least two spaces "<<endl; 

     } 
     else 
     { 
      cout<<" contains less then two spaces "<<endl; 

     } 
      } 


    else 
    { 

     cout<<" no spaces "<<endl; 
    } 

    } 

int main() 
{ 

    string_get(); 



    return 0; 
} 

當我運行這段代碼,輸入一些字符串,它工作正常,但有這樣的問題,即它說,該試驗這個代碼中有bug,我被要求修復它,但是我看不到哪個bug在這裏?可能string是NULL?或者string不包含任何空格?哪種情況我不得不考慮?

+5

stooooooooooooooooop downvoting – 2012-04-17 07:59:37

+3

爲什麼選票過低? – Nick 2012-04-17 08:00:39

+0

聽起來更像是一個煉獄怪物(或一羣綿羊!) – Nick 2012-04-17 08:03:27

回答

3

提出問題的人可能會認爲find的參數pos需要在[0, length)的範圍內。然而,這並非如此,從標準21.3.6.3/2:

返回:xpos如果函數可以爲xpos確定一個這樣的值。 否則,返回npos。

+0

這很好,我不知道這個規則,也許不是作者,所以不是downvoting,最好是發佈這樣的規則,非常感謝 – 2012-04-17 08:22:42

+0

+1你是對的,我(錯誤地)認爲輸入錯誤參數被認爲是錯誤的。 – 2012-04-17 08:56:19

0

有一個小錯誤。可能沒有可用的輸入。您沒有檢查getline(cin,text);的返回值。這不太可能發生;你需要有例如輸入重定向和一個空的輸入文件。

相關問題