抛出 'std::out_of_range' what() 的实例: basic_string::at_n __n >= this->size()
throwing an instance of 'std::out_of_range' what(): basic_string::at_n __n >= this->size()
我无法将字符串传递给函数。实际上我可以建立&运行我的程序,但是它给了我这个错误(我输入了'spoon'):
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()对我来说都不起作用。希望你能帮助我-谢谢:)
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 ++;
}
这个循环:
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
导致异常被抛出。你需要检查你是否到达了字符串的末端!
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 是std :: set&lt; std :: future&gt;不可能存在
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- 使用 std::vector<boost::shared_ptr<Base_Class>> 或 boost::p tr_vector 的性能注意事项是什么<Base>
- std::map<std::set, double> AND std:<long>map< std::p air<long, long>, double>
- 如何获取std::vector<DMatch>