【发布时间】:2017-09-14 20:34:35
【问题描述】:
我正在开发一个具有输入文件的程序,它可以添加、删除或打印字符串。我的print 函数正在工作,但是当我取消注释显示的代码行时出现分段错误。
int main()
{
vector <string> vec; //Creates an empty vector
string command;
string word;
int index;
ifstream fin;
fin.open("datalabvec.dat"); //Opens the input file
if (!fin)
cout << "The input file does not exist" << endl << endl;
else
{
fin >> command;
while (fin)
{
if (command =="Add")
{
fin >> word >> index;
//addVec (vec, word, index);
}
//if (command == "Remove")
//{
//fin >> index;
//remVec (vec, index);
//}
// else //Print function
{
printVec(vec);
}
fin >> command;
}
}
}
void addVec(vector <string> &v, string word, int ind)
{
int size = v.size();
if (ind > size + 1)
cout << "Invalid adding at index " << ind << endl;
else
{
v.insert(v.begin()+ind, word);
}
}
void remVec(vector <string> &v, int ind)
{
int size = v.size();
if (ind > size)
cout << "Invalid removing at index " << ind << endl;
else
{
v.erase(v.begin() + ind);
}
}
void printVec(const vector <string> v)
{
int size = v.size();
for (int i = 0; i < size; i++)
{
cout << v[i] << "\t";
}
cout << endl;
}
输入文件
Remove 0
Add Student 0
Add Kid 0
Add Final 1
Add Grow 1
Add Note 2
Add Bad 6
Remove 5
Add Worse -1
Print
Add Rich 5
Remove 1
Remove 7
Add Mind 2
Remove 3
Print
【问题讨论】:
-
您提到了注释代码,但您的示例中没有任何 cmets...实际上,您的打印功能也丢失了。
-
那是因为您的两个函数都允许 UB 用于某些输入。修正你的比较。
-
有问题吗?
标签: c++ vector segmentation-fault