【发布时间】:2021-03-28 22:40:38
【问题描述】:
我正在尝试运行一个代码,从文本文件中对泰坦尼克号幸存者的年龄进行排序。它编译得很好,但是当我选择选项 B(选项 A 尚未编写)时,程序终止只是说“分段错误”。 这是文本文件的一个小样本供参考。
29 1stClass 正确
0.9 第一类为真
2 1stClass FALSE
30 一等假
我已将错误隔离到处理文件的块(//实际处理),但我不确定究竟是什么错误。
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <fstream>
#include <ctype.h>
void sortSurvivors();
void sortAgesLiving();
int main()
{
char options;
std::cout << "Titanic Data \nOptions \nA) Display count of people who lived and died... \nB) Display count of people who lived by age... \nPlease select option (A-B)...";
std::cin >> options;
switch (options)
{
case 'A':
sortSurvivors();
break;
case 'B':
sortAgesLiving();
break;
}
}
void sortSurvivors()
{
}
void sortAgesLiving()
{
std::ifstream inputFile;
std::string filename = "TitanicData.txt";
std::string age;
std::string classBoat;
std::string survival;
bool survived;
int eldest = 0;
//pre-sort processing
while (inputFile >> age >> classBoat >> survival)
{
int ageConv = stoi(age);
//G is for the ghetto fix I am pulling here, because I recieve an error when using "TRUE" as a string
char gchar = 'G';
survival += gchar;
if (survival == "TRUEG")
{
survived = true;
}
else
{
survived = false;
}
if (eldest < ageConv)
{
eldest = ageConv;
}
}
//initialize vector
std::vector<int> survivorVector;
for (int i = 0; i < eldest; i++)
{
survivorVector.push_back(0);
}
inputFile.open(filename);
//actual processing (ERROR HERE)
if (inputFile)
{
while (inputFile >> age >> classBoat >> survival)
{
int ageConv = stoi(age);
if (survived = true)
{
survivorVector[ageConv] = survivorVector[ageConv] + 1;
}
for (int j = 0; j <= eldest; j++)
{
std::cout << j << "\t" << survivorVector[j] << "\n";
}
}
// Close the file.
inputFile.close();
}
else
{
std::cout << "I don't know what broke, but uhhhhhhhhhh oops.";
}
}
像往常一样,我确定这是我忽略的一些愚蠢的事情。
【问题讨论】:
-
你能证明你在任何地方都在使用
[]运算符,比如survivorVector[ageConv]或survivorVector[j]-- 你能从逻辑上证明你是不是 i> 访问数组中的负数或不存在的索引,它总是在 0 到小于向量大小的 1 之间?除非您能证明这一点,否则这是可能导致崩溃的原因之一。 ...实际上我可以看到这个错误。