我無法將字符串傳遞給函數。 其實我可以建立&運行我的程序,但它給了我這個錯誤(我在「勺子」類型):拋出'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()不適用於我。希望你能幫助我 - 謝謝你:)
您在for循環範圍內聲明瞭'result'。在循環之前聲明它。 –