2015-09-12 85 views
0

我無法將字符串傳遞給函數。 其實我可以建立&運行我的程序,但它給了我這個錯誤(我在「勺子」類型):拋出'std :: out_of_range'的實例what():basic_string :: at_n __n> = this-> size()

terminate called after throwing an instance of 'std::out_of_range' 
    what(): basic_string::at_n __n (which is 5) >= this->size() (which is 5) 
Aborted (core dumped) 

我想建立一個程序能夠在一個問題來識別不同的關鍵字和回答

#include <iostream> 
#include <string> 

using namespace std; 

int result; 

//returns value of the analysation case 
int analyze(string w) 
{ 
    if(w == "knife"){return 1;} 
    if(w == "spoon"){return 2;} 
    if(w == "fork"){return 3;} 
    return 0; 
} 

int main() 
{ 
    string input; 
    cin >> input; 
    for(int pos = 0; pos < input.length(); pos++) //as long the current letter is within the string 
     { 
      string word = "";   //resetting stored word 
      while(input.at(pos) != ' ') //as long the current letter is not a space => goes trough a whole word 
      { 
       word += input.at(pos); //add the current letter to the current word 
       pos ++; 
      } 
      int result = analyze(word); //gets word analyzation result 
     } 

    switch(result) 
    { 
     case 1: 
      cout << "do something (1)"; break; 
     case 2: 
      cout << "do something (2)"; break; 
     case 3: 
      cout << "do something (3)"; break; 
     default: 
      cout << "I do not understand"; 
    } 
    return 0; 
} 

另外我無法通過for() - 循環傳遞'result'。我讀過編譯器會銷燬for() - 循環中使用的所有函數,但我不知道如何解決它。使用while()不適用於我。希望你能幫助我 - 謝謝你:)

+0

您在for循環範圍內聲明瞭'result'。在循環之前聲明它。 –

回答

1

vector::at()會拋出,如果你嘗試訪問出界。

問題是您增加了pos並檢查空間。如果你的輸入字符串沒有空間呢?

while(input.at(pos) != ' ') /* You should also abort when pos >= input.length() */ 
{ 
    word += input.at(pos); //add the current letter to the current word 
    pos ++; 
} 
1

這個循環:

while(input.at(pos) != ' ') //as long the current letter is not a space => goes trough a whole word { word += input.at(pos); //add the current letter to the current word pos ++; }

意志,如果字符串包含空格(或沒有更多的空間),晃過字符串的結尾。此時,input.at導致異常被拋出。你需要檢查你是否已經到達了你的字符串的末尾!

相關問題