c++ - 在 char 之后插入空格函数在代码之外工作但在 C++ 中返回错误
问题描述
我做了一个在特定字符后插入空格的函数,它适用于任何长字符,分离时的任何字符。像现在
using namespace std;
insert_spaces_before_delims(string a)
{
vector<int> found;
int temp;
int i=0;
//string a="Ahmeed+Khaled+awwad=Ahmedd-AWWAd"; //string be a parameter
temp = a.find_first_of("+-="); // chars be parameters if need to change
found.push_back(temp);
a.insert(found[i]," ");
while(a.find_first_of("+-=",found[i]+2)!= string::npos)
{
temp = a.find_first_of("+-=",found[i]+2);
found.push_back(temp);
a.insert(found[i+1]," ");
i++;
}
}
int main(void)
{
string equation;
getline(cin,equation);
insert_spaces_before_delims(equation);
//the output is the string with spaces before every +,- and =
}
我在返回该错误时调试函数“在抛出 'std::out_of_range'what() 的实例后调用终止:basic_string::replace: __pos (即 4294967295) > this->size() (即 0)”
按条件 (==string::npos) 为什么它再次出现在代码中并停止代码 continue ,只需返回错误并结束程序。
struct variable_content
{
//string coefficient; // coefficient of x ( value before x)
int value; // value of X = coefficient but in another type
string order; // order (number ) of x (number after x)
};
spilit__each_string(string,char,variable_content,vector<string>,vector<variable_content>);
spliting_each_variable(char ,variable_content ,vector<string> ,vector<variable_content>);
insert_spaces_before_delims(string );
int main()
{
int number_equations;
string equation; //receive string
vector<string> equations; // vector for equations input from user
vector<string> variables; // initial empty vector of string for each var as strings at all
vector<variable_content> variable; //initial empty vector of struct for each var
char delim[] = " ";
char delim1[]="xX";
cin>>number_equations;
number_equations++;
variable_content temp;
for (int i=0; i<number_equations;i++)
{
getline(cin,equation); //worked
//***the problem function , if i commented it the code works fine**** insert_spaces_before_delims(equation); //return error and stop the code equations.push_back(equation); //worked //make a temp struct and put tok1 in coefficient of it spilit__each_string(equation, delim,temp,variables,variable);//worked spliting_each_variable(delim1,temp ,variables,variable); //worked } //printing vector of struct of every variable for(int y=0; y<variable.size();y++) { cout<<variable[y].value<<"\t"<<variable[y].order<<endl; } }
重要部分和整个代码在github上的链接。https://github.com/AhmedKAwwad/Split-String-into-vector/blob/master/main.cpp
解决方案
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ 这个链接让我调试我的代码,发现在我的代码中混合了 cin>> 和 getline 会出错,然后我使用 getline 然后将字符串转换为整数感谢评论
推荐阅读
- javascript - Pass JavaScript object to controller
- c# - C# Net Core:在 API 中启用 Cors 后,仍处于 CORS 策略阻止状态
- ios - 将浮点数限制为小数点后两位,并为 Swift 中的数字提供逗号分隔格式
- ios - 使用 Swift 4 解码嵌套 JSON 只返回一个对象
- javascript - 如何通过按键访问 keyup 中的事件
- r - 分别给出月份和年份时的ggplot直方图
- react-native - 任何人都可以帮助如何在反应原生应用程序中实现视频通话功能吗?
- python - 神经网络在训练时为每个输入预测相同的输出类
- r - R包开发如何抑制依赖包生成的消息?
- c# - 按属性分组时获取“数量”的总和